Sub topic 12
Customizing 401 and 403 responses
This chapter assumes you can define a SecurityFilterChain bean, you know how authorizeHttpRequests rules work, and you understand the difference between authentication and authorization from earlier chapters. Here you will control what a client receives when a request is rejected.
Two failures, two handlers
Spring Security separates two kinds of rejection. Each one has its own extension point.
| Situation | Status | Handler interface |
|---|---|---|
| No valid credentials, or the caller is anonymous | 401 Unauthorized | `AuthenticationEntryPoint` |
| Authenticated, but not allowed to do this | 403 Forbidden | `AccessDeniedHandler` |
The names are misleading. 401 means "not authenticated", even though the status text says "Unauthorized". 403 means the caller is known but lacks permission.
Why you would customize them
The defaults work, but they are not API friendly. With HTTP Basic, the 401 response carries a WWW-Authenticate header and an empty body. A 403 has an empty body too. Clients usually want a JSON body with a stable shape, so they can show a message or log a code.
Writing a JSON entry point and handler
Both interfaces have a single method that receives the request, the response, and the exception. Write the JSON yourself with the response writer.
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class JsonSecurityErrors implements AuthenticationEntryPoint, AccessDeniedHandler {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex) throws IOException {
write(response, HttpServletResponse.SC_UNAUTHORIZED,
"{\"error\":\"unauthorized\",\"message\":\"Authentication is required\"}");
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException ex) throws IOException {
write(response, HttpServletResponse.SC_FORBIDDEN,
"{\"error\":\"forbidden\",\"message\":\"You do not have access to this resource\"}");
}
private void write(HttpServletResponse response, int status, String body) throws IOException {
response.setStatus(status);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(body);
}
}The messages are fixed strings on purpose. Do not copy ex.getMessage() into the body, because exception text can reveal internal details.
Registering them in the filter chain
Use the exceptionHandling customizer on the HttpSecurity object.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class ErrorHandlingConfig {
@Bean
SecurityFilterChain api(HttpSecurity http, JsonSecurityErrors errors) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.exceptionHandling(ex -> ex
.authenticationEntryPoint(errors)
.accessDeniedHandler(errors));
return http.build();
}
}With HTTP Basic, httpBasic installs its own entry point for failed logins. If you also want it to use your JSON body, pass your entry point to it: .httpBasic(b -> b.authenticationEntryPoint(errors)). Keep the WWW-Authenticate header in mind, since browsers use it to show a login prompt. For a pure API you may prefer to omit it.
For a JWT resource server, set the entry point on the oauth2ResourceServer customizer too, with oauth2.jwt(...).authenticationEntryPoint(errors). Otherwise bad tokens still get the default bearer response.
Common errors
- Using
@ControllerAdvicefor these cases. Security filters run before the dispatcher servlet, so an advice class never sees a 401 or 403 raised by the filter chain. Use the two handlers above. - Expecting 401 from an anonymous user on a forbidden path. An anonymous caller who fails a rule goes to the entry point, so the status is 401. A logged-in caller who fails the same rule gets 403.
- Method security exceptions. An
AccessDeniedExceptionthrown by@PreAuthorizeis translated by the same filter, so your handler also covers it, as long as the exception reaches the filter chain unchanged. - Wrong content type. Forgetting
setContentTypemakes clients treat your JSON as plain text.
Exercise
A request with a valid login but the role USER calls an endpoint that requires ADMIN. Which handler runs, and what status does the client get?
Show answer
The AccessDeniedHandler runs, because the caller is authenticated but not permitted. The client gets 403. The AuthenticationEntryPoint would run only if the caller were anonymous or had invalid credentials, giving 401.
Exercise
Why can't a @ControllerAdvice method customize the 401 response produced for a missing token?
Show answer
The rejection happens inside the security filter chain, before the request reaches the dispatcher servlet and any controller advice. You must configure an AuthenticationEntryPoint through exceptionHandling instead.