Sub topic 12
Understanding 401, 403, and error responses
This chapter assumes you have a working JWT resource server, as built in the setup chapters. It covers what the API returns when a request fails, and how to change those responses.
401 and 403 mean different things
- 401 Unauthorized means authentication failed. The server could not establish who the caller is. The token is missing, malformed, expired, badly signed, or fails issuer or audience checks.
- 403 Forbidden means authentication succeeded but authorization failed. The server knows who the caller is, and that caller lacks the required authority.
Fixing a 401 means getting a better token. Fixing a 403 means getting a token with different scopes or roles.
What Spring Security sends by default
The resource server DSL installs two handlers. BearerTokenAuthenticationEntryPoint produces 401 responses. BearerTokenAccessDeniedHandler produces 403 responses. Both add a WWW-Authenticate header, as RFC 6750 defines.
| Situation | Status | WWW-Authenticate |
|---|---|---|
| No `Authorization` header | 401 | `Bearer` |
| Expired or invalid token | 401 | `Bearer error="invalid_token", error_description="..."` |
| Valid token, missing authority | 403 | `Bearer error="insufficient_scope", ...` |
A request with no token gets a bare Bearer challenge, with no error code. This is intentional. The client did not attempt authentication, so there is nothing to report as invalid.
The error_description can include details such as Jwt expired at .... This helps debugging, but you may not want to expose it in production.
Customizing the responses
You can replace either handler in the oauth2ResourceServer block. The example below returns a JSON body. It also keeps the WWW-Authenticate header, which clients and proxies rely on.
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
.authenticationEntryPoint((request, response, ex) -> {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Bearer");
response.setContentType("application/json");
response.getWriter().write("{\"error\":\"unauthorized\"}");
})
.accessDeniedHandler((request, response, ex) -> {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("application/json");
response.getWriter().write("{\"error\":\"forbidden\"}");
}));
return http.build();
}Overriding the entry point replaces the default completely. If you drop the WWW-Authenticate header, clients lose the standard signal about the expected scheme and the failure reason.
Common errors
- A 403 where you expected 401. An unauthenticated request that reaches a rule requiring a specific authority should still produce 401. Check that
oauth2ResourceServeris configured on this filter chain. Without it, no bearer entry point is registered. - A 500 from
@PreAuthorize. Method security throwsAccessDeniedExceptionfrom inside the controller call. A@ControllerAdvicewith a broad@ExceptionHandler(Exception.class)catches it and returns 500. RethrowAccessDeniedException, or handle it explicitly as 403. - A 401 for a token that looks valid. Decode the token and compare
iss,aud, andexpagainst your decoder's validators. Clock differences between servers also cause expiry failures. - A 403 for the right user. The scope or role is probably mapped to a different authority name. Scopes become
SCOPE_orders.read, while a custom roles claim with theROLE_prefix becomesROLE_admin.
Exercise
A client sends a correctly signed token that has expired. Which status and header does the default resource server return, and which handler produces them?
Show answer
It returns 401 with a header like WWW-Authenticate: Bearer error="invalid_token", error_description="Jwt expired at ...". BearerTokenAuthenticationEntryPoint produces it. The token never counts as authenticated, so the request never reaches authorization and cannot be a 403.