Sub topic 12
Customizing 401 and 403 responses
This chapter assumes you can build a Spring Boot REST controller, write a SecurityFilterChain bean, and read basic HTTP status codes. It also assumes you know the difference between authentication (who are you?) and authorization (what may you do?) from earlier chapters.
By default, Spring Security answers failures with its own format. A REST client usually wants a predictable JSON body instead. This chapter explains where 401 and 403 responses come from and how to replace them.
401 versus 403
The two codes mean different things, and Spring Security decides between them in one place.
| Status | Meaning | Typical cause |
|---|---|---|
| 401 Unauthorized | The caller is not authenticated. | No credentials, a wrong password, an expired or malformed token. |
| 403 Forbidden | The caller is authenticated but not allowed. | Missing role or authority, or a rejected CSRF token. |
The name "Unauthorized" is historical. In practice, 401 means "I don't know who you are" and 403 means "I know who you are, and the answer is no."
Where the responses are produced
Both failures are raised as exceptions inside the filter chain, in a filter named ExceptionTranslationFilter. This filter sits near the end of the chain, just before the authorization check. It catches two exception types and hands each to a dedicated handler.
| Exception | Handler interface | Default behavior |
|---|---|---|
| `AuthenticationException` | `AuthenticationEntryPoint` | Depends on the login mechanism. HTTP Basic sends 401 with a `WWW-Authenticate` header. |
| `AccessDeniedException` | `AccessDeniedHandler` | Sends 403 with an empty or default error body. |
There is one subtle rule. If an AccessDeniedException is thrown for an anonymous user (nobody is logged in), the filter treats it as an authentication problem and calls the AuthenticationEntryPoint. That is why an unauthenticated request to a protected path yields 401 and not 403. The AccessDeniedHandler is called only when the caller is authenticated.
What you see by default
With the HTTP Basic configuration from earlier chapters, an unauthenticated call looks like this:
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm"
Content-Length: 0The body is empty. For an authenticated user lacking the role, Spring Boot may forward to its /error page, which produces a JSON body with timestamp, status, error, and path fields. That format is Spring Boot's, not Spring Security's, and it is not something you control from the security configuration.
A consistent JSON error body
A small record keeps both handlers returning the same shape. This example uses Jackson's ObjectMapper, which Spring Boot already provides.
import java.time.Instant;
public record ApiError(Instant timestamp, int status, String error, String message, String path) {
}Instant serializes correctly only if the jackson-datatype-jsr310 module is registered. Spring Boot's auto-configured ObjectMapper does this for you, so inject that bean rather than calling new ObjectMapper().
Writing the entry point (401)
An AuthenticationEntryPoint receives the request, the response, and the exception. It must write the response itself.
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final ObjectMapper mapper;
public JsonAuthenticationEntryPoint(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException ex) throws IOException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setHeader("WWW-Authenticate", "Basic realm=\"api\"");
var body = new ApiError(Instant.now(), 401, "Unauthorized",
"Authentication is required to access this resource",
request.getRequestURI());
mapper.writeValue(response.getOutputStream(), body);
}
}Two details matter here. First, the WWW-Authenticate header is part of the HTTP contract for 401 responses, so keep it. Use the scheme that matches your setup, such as Basic here or Bearer for tokens. Second, do not echo ex.getMessage() to the client. Messages can reveal internal detail, such as whether a username exists.
Writing the access denied handler (403)
The handler for 403 follows the same pattern.
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
@Component
public class JsonAccessDeniedHandler implements AccessDeniedHandler {
private final ObjectMapper mapper;
public JsonAccessDeniedHandler(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException ex) throws IOException {
response.setStatus(HttpStatus.FORBIDDEN.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
var body = new ApiError(Instant.now(), 403, "Forbidden",
"You do not have permission to perform this action",
request.getRequestURI());
mapper.writeValue(response.getOutputStream(), body);
}
}Registering both in the filter chain
Wire the two components into exceptionHandling. The entry point you register here applies to every authentication mechanism that does not set its own.
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.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class ApiSecurityConfig {
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http,
JsonAuthenticationEntryPoint entryPoint,
JsonAccessDeniedHandler deniedHandler) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.exceptionHandling(ex -> ex
.authenticationEntryPoint(entryPoint)
.accessDeniedHandler(deniedHandler));
return http.build();
}
}A caller with no credentials now gets this:
{
"timestamp": "2026-12-01T09:11:46.892Z",
"status": 401,
"error": "Unauthorized",
"message": "Authentication is required to access this resource",
"path": "/api/admin/users"
}Bad credentials are a separate path
With HTTP Basic, a wrong password does not go through ExceptionTranslationFilter. BasicAuthenticationFilter catches the failure itself and calls its own entry point. When you call httpBasic(Customizer.withDefaults()), Spring Security uses the entry point from exceptionHandling if one is registered. If you see Basic's default empty 401 for bad passwords while your custom body appears for missing credentials, check that you registered the entry point on the same chain.
For bearer tokens it works differently. The OAuth2 resource server has its own BearerTokenAuthenticationEntryPoint and BearerTokenAccessDeniedHandler, which set a WWW-Authenticate: Bearer header with error and error_description attributes as RFC 6750 describes. Setting exceptionHandling alone does not replace them. You configure the resource server directly:
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
.authenticationEntryPoint(entryPoint)
.accessDeniedHandler(deniedHandler))If you do this, remember to use a Bearer challenge in your entry point's WWW-Authenticate header, not Basic.
Failures that never reach these handlers
Not every error comes from the filter chain. Keep the boundaries clear.
- Exceptions thrown in controllers.
@RestControllerAdvicehandles errors from controller code. It does not see exceptions raised in filters, because filters run before theDispatcherServlet. - Method security.
@PreAuthorizethrowsAccessDeniedExceptionfrom inside a controller or service call. That exception travels back up through the chain and reachesExceptionTranslationFilter, so yourAccessDeniedHandlerstill produces the response. However, if a@RestControllerAdvicehas an@ExceptionHandler(Exception.class)method, it may catch the exception first and return 500. RethrowAccessDeniedExceptionor handle it explicitly in that case. - CSRF failures. A rejected CSRF token is an
AccessDeniedException(InvalidCsrfTokenExceptionorMissingCsrfTokenException), so it also ends in your 403 handler. The message you return should not suggest a permissions problem. - Errors dispatched to
/error. When the container forwards to/error, the request is dispatched again. In recent Spring Security versions the error dispatch is also secured. If/errorrequires authentication, a failure may be shown as 401 instead of the original status. Permit/errorif you rely on Spring Boot's error page.
.requestMatchers("/error").permitAll()Delegating to HandlerExceptionResolver
Some teams prefer to keep all error formatting in one @RestControllerAdvice. You can route security exceptions there by forwarding to the HandlerExceptionResolver bean.
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
@Component
public class DelegatingEntryPoint implements AuthenticationEntryPoint {
private final HandlerExceptionResolver resolver;
public DelegatingEntryPoint(
@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
this.resolver = resolver;
}
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException ex) {
resolver.resolveException(request, response, null, ex);
}
}An @ExceptionHandler(AuthenticationException.class) method in your advice then builds the response. This gives one place for all error formats. The cost is an extra moving part: if the advice has no matching method, the resolver returns nothing and the response stays empty with the container's default status.
Common mistakes
- Returning 403 for anonymous callers. This usually means a custom
AccessDeniedHandlerwas registered but no entry point exists, so Spring falls back toHttp403ForbiddenEntryPoint. Always set both. - Missing content type. Without
setContentType, clients may receive JSON labeled astext/plain. - Writing the body, then calling
sendError.sendErrorcommits the response and triggers the/errordispatch. Pick one approach. - Leaking details. Do not include exception messages, stack traces, or role names in the body.
- Forgetting the challenge header. A 401 without
WWW-Authenticateviolates the HTTP specification, and some clients rely on it.
Exercise
A client calls /api/admin/users with no credentials and receives a 403 with your custom JSON body, not a 401. You registered an AccessDeniedHandler through exceptionHandling and nothing else. What is the likely cause, and how do you fix it?
Show answer
Without an AuthenticationEntryPoint, Spring Security falls back to a default entry point that returns 403 rather than 401 (here Http403ForbiddenEntryPoint), because no authentication mechanism supplied a challenge. Register your own entry point with .authenticationEntryPoint(entryPoint) inside exceptionHandling, and return status 401 with a WWW-Authenticate header. Anonymous failures go to the entry point, and only authenticated failures reach the access denied handler.
Exercise
Your API uses .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())), and you added a custom entry point under exceptionHandling. Requests with an expired token still return the default empty body with a WWW-Authenticate: Bearer error="invalid_token" header. Why, and what is the fix?
Show answer
The resource server installs its own BearerTokenAuthenticationEntryPoint for failures in the bearer token filter, and it takes precedence there. Set the entry point on the resource server itself with .oauth2ResourceServer(o -> o.jwt(...).authenticationEntryPoint(entryPoint)). Also use a Bearer challenge in the header.