Changing the error response when a JWT is rejected in Spring Security
401 Unauthorized with a WWW-Authenticate: Bearer header for a rejected tokenShort answer
A resource server answers a bad token with 401 and a WWW-Authenticate header, and a valid token without enough rights with 403. Both are customised on oauth2ResourceServer: authenticationEntryPoint for failed authentication, accessDeniedHandler for denied access. Setting only one leaves the other default.
Fix it fast
1Find out which cause you have
Send one request with no token, one with a broken token and one with a valid token for the wrong role. Note which status each gets; the status tells you which handler to change.
curl -i http://localhost:8080/api/admin curl -i -H "Authorization: Bearer not-a-jwt" http://localhost:8080/api/admin curl -i -H "Authorization: Bearer $USER_TOKEN" http://localhost:8080/api/admin2Match what you see, then jump to its fix
What does the error look like?
401 Unauthorized with a WWW-Authenticate: Bearer header for a rejected token403 Forbidden for a valid token that lacks the required authority
Cause 1 of 2
Authentication failures use the default entry point
1Check
When a bearer token is invalid the server replies 401 with a WWW-Authenticate header describing the error. The Javadoc describes authenticationEntryPoint as the hook that customizes how authentication failures are handled.
curl -i -H "Authorization: Bearer not-a-jwt" http://localhost:8080/api/admin2Fix
Set your own AuthenticationEntryPoint on the resource server DSL. Keep the WWW-Authenticate header when you write the body.
http.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
.authenticationEntryPoint((request, response, ex) -> {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write("{\"error\":\"unauthorized\"}");
}));3Verify
Repeat the broken-token request and read the body.
curl -i -H "Authorization: Bearer not-a-jwt" http://localhost:8080/api/adminConfirmed by docs.spring.io
Cause 2 of 2
Access denied responses use the bearer-token handler
1Check
BearerTokenAccessDeniedHandler turns an AccessDeniedException into an RFC 6750 response; for an authenticated OAuth 2.0 request it reports an insufficient scope error in the header.
curl -i -H "Authorization: Bearer $USER_TOKEN" http://localhost:8080/api/admin2Fix
Register an accessDeniedHandler on the same DSL.
http.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
.accessDeniedHandler((request, response, ex) -> {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write("{\"error\":\"forbidden\"}");
}));3Verify
Repeat the request with the low-privilege token.
curl -i -H "Authorization: Bearer $USER_TOKEN" http://localhost:8080/api/adminConfirmed by docs.spring.io
How do I stop it coming back?
- Test the three cases (no token, bad token, wrong role) with MockMvc so error shapes are fixed by tests.
- Return the same JSON shape from both handlers so clients parse one format.
- Keep the WWW-Authenticate header on 401 responses; clients and gateways rely on it.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Security
Jwts.parserBuilder() no longer compiles after upgrading JJWT
setSigningKey / parseClaimsJws / getBody shown as deprecated
JJWT 0.12.0 removed Jwts.parserBuilder() because Jwts.parser() now returns the builder itself.
3 causes, each with a fixSecurity
Spring Boot cannot find a ClientRegistrationRepository bean for OAuth2 login
APPLICATION FAILED TO START
Boot creates the ClientRegistrationRepository from spring.security.oauth2.client.registration properties.
3 causes, each with a fixSecurity
Spring Security fails to resolve the issuer configuration for a JWT or Keycloak
The identity server is up but the Spring app fails on the first token
Spring Security fetches the issuer's discovery document before it can validate tokens.
3 causes, each with a fixSecurity
Spring Security cannot verify the CSRF token because the session is gone
InvalidCsrfTokenException
By default Spring Security keeps the expected CSRF token in the HTTP session.
3 causes, each with a fixSecurity
POST requests return 403 in Spring Security because the CSRF token is missing
MissingCsrfTokenException
Spring Security checks a CSRF token on every request except GET, HEAD, TRACE and OPTIONS.
4 causes, each with a fixSecurity
A Microsoft Entra access token shows Invalid Signature when you check it yourself
Tokens that a Microsoft API receives might not always be a JWT that can be decoded
A token issued for Microsoft Graph is not meant for you to validate, so a failed signature check is expected.
2 causes, each with a fix