Video in progress
What do you configure in Spring Security to return 401 and 403 responses in your own JSON format?
An error that originates in a filter never reaches @RestControllerAdvice. So you write an AuthenticationEntryPoint for 401 and an AccessDeniedHandler for 403, and wire them into the SecurityFilterChain through exceptionHandling().
📖 Answer
The reason: if the token is missing or access is denied by a URL rule, the request stops in the filter chain. It never reaches the DispatcherServlet, and so never reaches the controller advice. By default the client gets a 401 with an empty body or an HTML page.
@Bean
SecurityFilterChain api(HttpSecurity http, ObjectMapper json) throws Exception {
http
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.exceptionHandling(e -> e
.authenticationEntryPoint((req, res, ex) ->
write(res, json, HttpStatus.UNAUTHORIZED, "Avtorizatsiyadan o'tilmagan"))
.accessDeniedHandler((req, res, ex) ->
write(res, json, HttpStatus.FORBIDDEN, "Bu amal uchun huquq yetarli emas")));
return http.build();
}
private static void write(HttpServletResponse res, ObjectMapper json,
HttpStatus status, String detail) throws IOException {
ProblemDetail body = ProblemDetail.forStatusAndDetail(status, detail);
res.setStatus(status.value());
res.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE);
json.writeValue(res.getOutputStream(), body);
}
Subtle points:
- with a resource server,
oauth2ResourceServersets its own entry point (with theWWW-Authenticateheader). If you want to replace it, also provide yours insideo.authenticationEntryPoint(...); @PreAuthorizeerrors: thisAccessDeniedExceptionis thrown at the controller layer. If the advice has@ExceptionHandler(Exception.class), it swallows the exception and returns 500. Either catchAccessDeniedExceptionseparately in the advice, or rethrow it;- response format: if it's the same
ProblemDetailas the API's other errors, the frontend needs just one error handler; - don't reveal the reason in the message ("token expired" is enough, not "signing key does not match").
To verify: call with curl -i without a token and with the wrong role, and look at the status, Content-Type and body; lock it in with a @WebMvcTest test.
Sign up to mark studied questions and save your progress.