Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Security and hardening

Changing the error response when a JWT is rejected in Spring Security

Error401 Unauthorized with a WWW-Authenticate: Bearer header for a rejected token

Short 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.

  • Applies to Spring Boot 3.5, Spring Security 6.5, Java 21
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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/admin
  2. 2Match what you see, then jump to its fix

    1. 1401 and a WWW-Authenticate header describing the token errorAuthentication failures use the default entry pointFix
    2. 2403 for a valid token, with the reason only in the WWW-Authenticate headerAccess denied responses use the bearer-token handlerFix

What does the error look like?

  • 401 Unauthorized with a WWW-Authenticate: Bearer header for a rejected token
  • 403 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/admin

2Fix

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/admin

Confirmed by docs.spring.io

Did this fix it?

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/admin

2Fix

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/admin

Confirmed by docs.spring.io

Did this fix it?

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

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.