I’m building an API using Spring Boot 3.0.1 with Spring Security, I’ve built out the security filter chain and use custom exception handler in it to process exceptions in authentication (for example when I get request without correct JWT token). But this handler processing all others exceptions (such as invalid agruments in query) by default and in situation when I try to process invalid request I getting 401-unauthorised
exception from my handler by default instead of 500-internal server error
.
What should I do for make my custom handler in FilterChain process ONLY authentication exceptions?
My SecurityChain config:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.exceptionHandling(
exception -> exception.authenticationEntryPoint(unauthorizedEntryPoint)
)
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/taskservice/api/v1/auth/**").permitAll()
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated()
)
.sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class)
;
return http.build();
}
My custom exception handler:
@Component
@Slf4j
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
log.error("Unauthorized error: {}", authException.getMessage());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
LoginResponseError body = LoginResponseError.builder()
.status(HttpServletResponse.SC_UNAUTHORIZED)
.error("Unauthorized")
.timestamp(Instant.now())
.message(authException.getMessage())
.path(request.getServletPath())
.build();
final ObjectMapper mapper = new ObjectMapper();
// register the JavaTimeModule, which enables Jackson to support Java 8 and higher date and time types
mapper.registerModule(new JavaTimeModule());
// ask Jackson to serialize dates as strings in the ISO 8601 format
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
mapper.writeValue(response.getOutputStream(), body);
}
}
I tried to .requestMatchers("/error**").permitAll()
but it leads to opposite situation: Im getting 500-internal server error
errors for all errors, even for problems with authentication
Maksim Artsishevskiy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.