{"record":{"id":"4703599e5957a1ae","repo":"spring-projects/spring-security","slug":"invalid-token-470359","errorCode":"invalid_token","errorMessage":"Bearer token is malformed","messagePattern":"Bearer token is malformed","errorType":"error_code","errorClass":"OAuth2AuthenticationException","httpStatus":401,"severity":"error","filePath":"oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java","lineNumber":100,"sourceCode":"\t\tif (accessToken != null && accessToken.isBlank()) {\n\t\t\tBearerTokenError error = BearerTokenErrors\n\t\t\t\t.invalidRequest(\"The requested token parameter is an empty string\");\n\t\t\tthrow new OAuth2AuthenticationException(error);\n\t\t}\n\n\t\treturn accessToken;\n\t}\n\n\tprivate @Nullable String resolveFromAuthorizationHeader(HttpServletRequest request) {\n\t\tString authorization = request.getHeader(this.bearerTokenHeaderName);\n\t\tif (!StringUtils.startsWithIgnoreCase(authorization, \"bearer\")) {\n\t\t\treturn null;\n\t\t}\n\n\t\tMatcher matcher = authorizationPattern.matcher(authorization);\n\t\tif (!matcher.matches()) {\n\t\t\tBearerTokenError error = BearerTokenErrors.invalidToken(\"Bearer token is malformed\");\n\t\t\tthrow new OAuth2AuthenticationException(error);\n\t\t}\n\n\t\treturn matcher.group(\"token\");\n\t}\n\n\tprivate @Nullable String resolveAccessTokenFromQueryString(HttpServletRequest request) {\n\t\tif (!this.allowUriQueryParameter || !HttpMethod.GET.name().equals(request.getMethod())) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn resolveToken(request.getParameterValues(ACCESS_TOKEN_PARAMETER_NAME));\n\t}\n\n\tprivate @Nullable String resolveAccessTokenFromBody(HttpServletRequest request) {\n\t\tif (!this.allowFormEncodedBodyParameter\n\t\t\t\t|| !MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType())\n\t\t\t\t|| HttpMethod.GET.name().equals(request.getMethod())) {\n\t\t\treturn null;","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/spring-projects/spring-security/blob/96852e8860138a482cb13d1479573f24ff6443c6/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java#L82-L118","documentation":"This error is thrown by DefaultBearerTokenResolver when the Authorization header starts with 'Bearer ' but the remainder does not match the expected token pattern (a single non-whitespace token). The resolver treats any structurally invalid bearer credentials as an OAuth2AuthenticationException carrying the invalid_token error code, per RFC 6750. It signals that the client sent credentials the framework cannot even parse, before any token validation occurs.","triggerScenarios":"Sending an Authorization header with a Bearer scheme whose value contains whitespace (e.g. a pasted token with a trailing newline or internal space), two tokens separated by a space, or an empty value after 'Bearer '. Also triggered by case/format variations that pass the prefix check but fail BearerTokenAuthenticationMatcher's regex, such as 'Bearer a b'.","commonSituations":"Tokens copied from logs or docs with wrapping whitespace; proxies or gateways mangling the header; misconfigured clients concatenating token type and value twice ('Bearer Bearer abc'); headers that include a newline from environment variable interpolation.","solutions":["Inspect the raw Authorization header and remove any whitespace/newlines inside or after the token value","Ensure the client sends exactly 'Authorization: Bearer <single-token>' with no extra spaces","Regenerate the token — some issuers emit tokens containing characters the resolver's pattern rejects","If you need custom schemes, supply a custom BearerTokenResolver instead of the default"],"exampleFix":"// before\nhttpHeaders.set(\"Authorization\", \"Bearer \" + token + \" \");\n// after\nhttpHeaders.set(\"Authorization\", \"Bearer \" + token.trim());","handlingStrategy":"validation","validationCode":"String auth = request.getHeader(\"Authorization\");\nif (auth != null && auth.startsWith(\"Bearer \")) {\n    String token = auth.substring(7).trim();\n    if (token.isEmpty() || token.matches(\".*\\\\s.*\")) {\n        throw new IllegalArgumentException(\"Malformed bearer token\");\n    }\n}","typeGuard":"boolean isValidBearerHeader(String header) {\n    return header != null && header.matches(\"^Bearer [!-~]+$\");\n}","tryCatchPattern":"try {\n    chain.doFilter(request, response);\n} catch (OAuth2AuthenticationException e) {\n    if (\"invalid_token\".equals(e.getError().getErrorCode())) {\n        response.setStatus(401);\n        response.setHeader(\"WWW-Authenticate\", \"Bearer error=\\\"invalid_token\\\"\");\n    }\n}","preventionTips":["Always trim tokens before building the Authorization header","Use a vetted HTTP client header API (set, not append)","Never copy tokens from wrapped log output without cleaning whitespace","Add an integration test asserting the exact header format"],"tags":["oauth2","bearer-token","http-header","spring-security"],"backgroundTag":"invalid-token-format","analyzedSha":"96852e8860138a482cb13d1479573f24ff6443c6","analyzedAt":"2026-09-10T23:25:23.477Z","contentChangedAt":"2026-09-10T23:25:23.477Z","schemaVersion":2},"datasetVersion":"2026-09-14T11:17:12.474Z"}