Sub topic 12
Understanding 401, 403, and error responses
This chapter assumes you have a working JWT resource server (the filter chain with oauth2ResourceServer(...jwt...) from earlier chapters), know the main HTTP status codes, and can read a Spring Security filter chain. It explains why the API returns 401 or 403, what the WWW-Authenticate header carries, and how to change the response body without breaking the protocol.
Two different questions
Spring Security separates two failures that clients often confuse.
- 401 Unauthorized means the server could not establish who the caller is. The token is missing, malformed, expired, or fails validation. The name is misleading: this status is about authentication.
- 403 Forbidden means the caller is known and the token is valid, but the caller lacks permission for this resource.
Retrying a 401 with a fresh or correct token can succeed. Retrying a 403 with the same identity cannot. A client needs to tell them apart. A 401 may mean "refresh the token and retry". A 403 means "stop and tell the user".
Where each response comes from
Two components in the filter chain produce these responses.
BearerTokenAuthenticationFilterreads theAuthorizationheader, hands the token to theJwtDecoder, and builds theAuthentication. If decoding or validation fails, it calls anAuthenticationEntryPoint. The default isBearerTokenAuthenticationEntryPoint, which returns 401.ExceptionTranslationFiltercatchesAccessDeniedExceptionthrown later byauthorizeHttpRequestsor@PreAuthorize. It then picks a handler based on who is calling.
The second step has a subtlety. If the caller is anonymous (no token was supplied), an AccessDeniedException is routed to the entry point and the client sees 401. If the caller is authenticated, it is routed to the AccessDeniedHandler and the client sees 403. This is why a request with no token to a protected URL gets 401, not 403.
Reading WWW-Authenticate
RFC 6750 defines how a bearer-token API reports problems. Every 401 carries a WWW-Authenticate header with the Bearer scheme. Spring adds an error attribute when it can say what went wrong.
| Situation | Status | WWW-Authenticate |
|---|---|---|
| No `Authorization` header on a protected URL | 401 | `Bearer` (no error attribute) |
| Header uses another scheme, such as `Basic` | 401 | `Bearer` |
| Expired token, bad signature, wrong issuer or audience | 401 | `Bearer error="invalid_token", error_description="..."` |
| Malformed header, such as two tokens in one header | 400 | `Bearer error="invalid_request"` |
| Valid token, missing authority | 403 | `Bearer error="insufficient_scope"` |
A missing token deliberately has no error attribute. RFC 6750 says that when the request lacks authentication information, the server should not add error details. It only advertises that Bearer is the expected scheme.
You can see the real behavior with curl. Replace the URL with your own:
curl -i http://localhost:8080/orders
curl -i -H "Authorization: Bearer not-a-real-token" http://localhost:8080/ordersThe first call returns 401 with WWW-Authenticate: Bearer. The second returns 401 with error="invalid_token" and a description such as An error occurred while attempting to decode the Jwt.
The 403 case is handled by BearerTokenAccessDeniedHandler. It adds error="insufficient_scope" to the header when the caller was authenticated with a bearer token. A client can read this and know that it should request a token with broader scopes, not a fresh copy of the same token.
Customizing the response body
The default 401 and 403 responses have an empty body. Many APIs want a JSON body in a consistent shape. Do not replace the default components outright. If you write a bare entry point that only sets the status, you lose the WWW-Authenticate header, and clients that follow RFC 6750 stop working correctly.
The safer pattern is to delegate to the Spring components for status and header, then add the body:
import java.io.IOException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
class JsonBearerEntryPoint implements AuthenticationEntryPoint {
private final BearerTokenAuthenticationEntryPoint delegate =
new BearerTokenAuthenticationEntryPoint();
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex) throws IOException {
delegate.commence(request, response, ex); // sets 401 and WWW-Authenticate
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(
"{\"error\":\"unauthorized\",\"message\":\"Missing or invalid access token\"}");
}
}
class JsonBearerAccessDeniedHandler implements AccessDeniedHandler {
private final BearerTokenAccessDeniedHandler delegate =
new BearerTokenAccessDeniedHandler();
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException ex) throws IOException, jakarta.servlet.ServletException {
delegate.handle(request, response, ex); // sets 403 and insufficient_scope
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(
"{\"error\":\"forbidden\",\"message\":\"Insufficient permissions\"}");
}
}The bodies are fixed strings on purpose. Writing exception messages into a hand-built JSON string risks both leaking internals and producing invalid JSON when the message contains quotes.
Register both on the resource server configurer, not on the generic exceptionHandling block. The resource server configurer applies them to the bearer-token filter as well as to access decisions:
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
.authenticationEntryPoint(new JsonBearerEntryPoint())
.accessDeniedHandler(new JsonBearerAccessDeniedHandler()));Method security and @ControllerAdvice
@PreAuthorize throws AccessDeniedException from inside the controller call. It reaches ExceptionTranslationFilter and becomes a 403 only if nothing catches it first. A common bug is a @ControllerAdvice with @ExceptionHandler(Exception.class) that turns every exception into a 500 response. That handler intercepts AccessDeniedException before the security filter sees it, and the client gets 500 instead of 403.
Failures that are not the client's fault
Not every authentication failure is a 401. If the JwtDecoder cannot fetch the JWK set because the authorization server is unreachable, that is a server-side problem. Spring typically treats it as an internal error and the client sees a 500 or 503-style failure instead of invalid_token. Monitor this separately, because telling clients "your token is invalid" would be wrong.
Verifying the behavior in tests
Test the header as well as the status, since clients depend on both. Using the jwt() post-processor from the testing chapter:
@Test
void missingTokenReturns401WithChallenge() throws Exception {
mockMvc.perform(get("/orders"))
.andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Bearer"));
}
@Test
void missingScopeReturns403WithInsufficientScope() throws Exception {
mockMvc.perform(get("/orders").with(jwt()))
.andExpect(status().isForbidden())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE,
containsString("insufficient_scope")));
}Needed imports are header from MockMvcResultMatchers, containsString from Hamcrest, and HttpHeaders from Spring. Testing invalid_token needs a real or mocked JwtDecoder that rejects the token, because jwt() skips decoding.
Common mistakes
- Using a custom entry point that only sets 401. Clients lose the
WWW-Authenticatechallenge. - Registering handlers on
exceptionHandlingonly. Bearer-token failures may still use the default handlers. Use theoauth2ResourceServerconfigurer. - Returning 403 for a missing token. This hides the retry path. A missing token is 401.
- Returning 401 for a missing authority. This makes clients refresh tokens in a loop that can never succeed.
- Echoing
ex.getMessage()into response bodies. This leaks internals.
Exercise
A client calls GET /admin/users with no Authorization header. The rule is .requestMatchers("/admin/**").hasAuthority("SCOPE_admin"). What status and WWW-Authenticate value does it get, and why is it not 403?
Show answer
It gets 401 with WWW-Authenticate: Bearer and no error attribute. The caller is anonymous, so the AccessDeniedException is routed by ExceptionTranslationFilter to the authentication entry point, not to the AccessDeniedHandler. The header has no error attribute because the request carried no authentication information.
Exercise
Your API returns 403 with WWW-Authenticate: Bearer error="insufficient_scope" to a user holding a valid token. A mobile client automatically refreshes its token and retries on every 401 and 403. Why is that a problem, and what should the client do instead?
Show answer
A refreshed token has the same scopes, so it hits the same 403 and the client loops. The client should refresh and retry only on 401 with invalid_token. On 403 insufficient_scope it should stop, or start a new authorization request asking for the extra scopes.