Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

A REST API must return a JSON body {"error": "unauthorized"} with 401 and {"error": "forbidden"} with 403 instead of the default responses. Write the configuration.

We implement an AuthenticationEntryPoint that sets status 401, the content type application/json and writes {"error": "unauthorized"}, and an AccessDeniedHandler that does the same with 403 and {"error": "forbidden"}, then register both in exceptionHandling() of the API's SecurityFilterChain. For bearer tokens we wrap BearerTokenAuthenticationEntryPoint so the WWW-Authenticate header is kept. These handlers only see security exceptions that reach the filter chain; exceptions thrown in controllers are handled by @ControllerAdvice first.

Why this question is asked

Client teams like predictable errors. A mobile app or a front end that receives an HTML error page, or an empty body with a bare status, has to guess what happened, and guesses become bugs. Interviewers ask this coding question because it checks that we know where Spring Security produces these responses, which two interfaces to implement, and the details that are easy to miss: keeping the WWW-Authenticate header and understanding which errors never reach these handlers. In this answer, we will see the default responses, write both handlers, register them, keep the bearer header, and look at how method security and @ControllerAdvice interact with them.

1What the Defaults Look Like

Spring Security answers refused requests from ExceptionTranslationFilter, the filter that catches security exceptions thrown by the authorization step. 'Not authenticated' goes to an AuthenticationEntryPoint, and 'authenticated but not allowed' goes to an AccessDeniedHandler. The defaults depend on the login method: a redirect to /login for form login, a 401 with an empty body for a resource server, a 403 from AccessDeniedHandlerImpl.

In a Boot application, a 403 from the default handler goes through response.sendError(), which triggers Boot's error page and produces Boot's standard error JSON. So clients may see different shapes depending on which path produced the error. Our task is to make both paths write one known body themselves.

Java
# Before
GET /api/orders -> 401, empty body, WWW-Authenticate: Bearer
GET /api/admin (user without role) -> 403, {"timestamp":"...","status":403,"error":"Forbidden","path":"/api/admin"}

2Writing the Two Handlers

Both interfaces have one method that receives the request, the response and the exception. We set the status and content type and write the body directly. Writing it ourselves, instead of calling sendError(), means no error dispatch and no surprises from the error page.

Java
final class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final AuthenticationEntryPoint 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: Bearer ...
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write("{\"error\": \"unauthorized\"}");
}
}
final class JsonAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException ex) throws IOException {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write("{\"error\": \"forbidden\"}");
}
}

Notice the delegate in the entry point. BearerTokenAuthenticationEntryPoint sets the status to 401 and adds the WWW-Authenticate header, including error="invalid_token" and a description when a token was rejected. It writes no body, so we can add ours after it. That header is part of the bearer token standard (RFC 6750); clients and libraries use it to decide whether to refresh a token, so we keep it rather than replacing it.

The bodies are constant strings here, so we do not need a JSON library. If the body grew, for example with a correlation id, we would serialise it with the application's JSON mapper; Boot 4 moves to Jackson 3, so check your version for the mapper type to inject. Without bearer tokens, the entry point would simply call response.setStatus(401) itself.

3Registering Them in the API Chain

We register both in the exceptionHandling() section of the SecurityFilterChain that covers the API. The resource server configuration also needs our entry point, because invalid tokens are rejected by the bearer token filter itself, before ExceptionTranslationFilter is involved.

Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint();
JsonAccessDeniedHandler deniedHandler = new JsonAccessDeniedHandler();
http.securityMatcher("/api/**")
.authorizeHttpRequests(a -> a
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o
.jwt(Customizer.withDefaults())
.authenticationEntryPoint(entryPoint) // invalid or expired token
.accessDeniedHandler(deniedHandler))
.exceptionHandling(e -> e
.authenticationEntryPoint(entryPoint) // no token at all
.accessDeniedHandler(deniedHandler)); // authenticated but not allowed
return http.build();
}
// After
// GET /api/orders, no token -> 401 {"error": "unauthorized"} WWW-Authenticate: Bearer
// GET /api/orders, expired token -> 401 {"error": "unauthorized"} WWW-Authenticate: Bearer error="invalid_token", ...
// GET /api/admin, user without role -> 403 {"error": "forbidden"}
Step throughWhich handler writes the response
  1. Token present but invalid?
    YesBearer filter failure -> our entry point: 401NoContinue
  2. Authorization denies the request?
    YesIs the user anonymous?NoRequest reaches the controller
  3. Anonymous?
    YesOur entry point: 401NoOur access denied handler: 403

3 steps in order. Play them, or step through them one at a time.

Notice that we set the entry point in two places. The bearer token filter has its own failure path for rejected tokens, and the exception handling section covers requests with no token, which only fail later at authorization. Registering the same objects in both makes every 401 identical.

4Errors Thrown Inside Controllers

These handlers live in the filter chain, so they only see exceptions that reach it. An exception thrown inside a controller is first offered to Spring MVC's exception handling: @ControllerAdvice classes with @ExceptionHandler methods. That is where application errors such as 404 or validation failures belong, and it is a separate place to apply the same JSON shape.

Method security is the interesting middle case. @PreAuthorize on a controller or service throws AccessDeniedException inside MVC. If no @ExceptionHandler matches it, it propagates out of the DispatcherServlet back to ExceptionTranslationFilter, and our handler writes the 403. But a broad handler for Exception.class in a @ControllerAdvice catches it first and typically turns it into a 500.

Java
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(AccessDeniedException.class)
void accessDenied(AccessDeniedException ex) throws AccessDeniedException {
throw ex; // let Spring Security's handler answer
}
@ExceptionHandler(Exception.class)
ResponseEntity<Map<String, String>> other(Exception ex) {
return ResponseEntity.status(500).body(Map.of("error", "internal"));
}
}
// @PreAuthorize("hasRole('ADMIN')") on a controller, called by a user -> 403 {"error": "forbidden"}

Notice that rethrowing keeps one source of truth for security responses. The alternative is to answer 403 with the same body directly in the advice, which also works as long as both places stay in sync.

5Follow-up questions

Why not call response.sendError(401) in the entry point?

sendError() triggers an error dispatch to Boot's /error endpoint, which builds its own body, and since Spring Security 6 the error dispatch is itself secured, so if /error is not permitted the body can be lost or the status changed. Writing the body directly avoids both problems.

Should a form-login part of the same application also return JSON?

No. Browsers should still be redirected to the login page. We keep a separate SecurityFilterChain for the browser pages, or use defaultAuthenticationEntryPointFor() with a matcher on /api/**, so only API requests get the JSON entry point.

How do we test the new responses?

With MockMvc and the security test support: perform a request without a token and expect status 401, the WWW-Authenticate header and the JSON body, then perform one with jwt() and a missing authority and expect 403 and the forbidden body.

6Conclusion

In this answer, we replaced the default security responses with JSON. An AuthenticationEntryPoint delegates to BearerTokenAuthenticationEntryPoint to keep the 401 status and WWW-Authenticate header and writes {"error": "unauthorized"}, and an AccessDeniedHandler writes 403 and {"error": "forbidden"}. We registered both in exceptionHandling() and in the resource server configuration, and saw that controller exceptions go to @ControllerAdvice first, so method security denials must be rethrown or handled there to keep the same shape.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd implement the two interfaces Spring Security uses for refusals. For 401, an AuthenticationEntryPoint whose commence method sets the status to 401, the content type to application/json, and writes the unauthorized body.

Then, if they want more

Since it's a bearer token API, I'd actually delegate to BearerTokenAuthenticationEntryPoint first, because it sets 401 and the WWW-Authenticate header with error invalid_token for expired or bad tokens, which clients use to decide to refresh, and it writes no body, so I add mine after it.

For 403, an AccessDeniedHandler that sets 403, the JSON content type and the forbidden body. I write the bodies directly instead of calling sendError, so there's no error dispatch to /error with a different body.

Then I register both in the API's SecurityFilterChain under exceptionHandling, and also on the oauth2ResourceServer configuration, because invalid tokens are rejected by the bearer filter's own failure path before ExceptionTranslationFilter. Then a missing token, an expired token and an anonymous request all give the same 401, and an authenticated user without the role gets the 403.

One caveat: these handlers only see exceptions that reach the filter chain. Controller errors go to @ControllerAdvice, and an AccessDeniedException from @PreAuthorize can be swallowed by a catch-all Exception handler and turned into a 500, so I'd rethrow it there or answer with the same body.

About this answer

Last updated
12 November 2026
Versions it names
Spring Security 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A REST API must return a JSON body {"error": "unauthorized"} with 401 and {"error"...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/60bda85870/