My CustomOAuth2AuthenticationEntryPoint is not called for a JwtValidationException

133 views Asked by At

I have a Spring Boot Rest backend protected with JWT, which is functioning properly with the use of oauth2ResourceServer as outlined below.

@Bean
 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  http
     .cors().configurationSource(corsConfigurationSource).and()
     .csrf().disable()  //Disable csrf, since we are using token based authentication, not cookie based
     .httpBasic(Customizer.withDefaults())
     .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
     //REF: https://mflash.dev/post/2021/01/19/error-handling-for-spring-security-resource-server/
     .exceptionHandling((exceptions) -> exceptions
        .authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint())
        .accessDeniedHandler(new CustomOAuth2AccessDeniedHandler())
      )
     .oauth2ResourceServer()
     .jwt()
     .jwtAuthenticationConverter(authenticationConverter());
....

From a security perspective, everything is working fine, and I receive appropriate tailored error responses from my CustomOAuth2AuthenticationEntryPoint() for most of the "problems".

This includes a JSON response with details about the issue.

However, if the token has expired or has been tampered with,this fires a JwtValidationException and this does NOT trigger my CustomOAuth2AuthenticationEntryPoint. While this doesn't pose a security problem, since I receive a 401 response, it lacks the additional JSON information.

How can I modify this behavior to provide additional details, similar to what is done in my CustomOAuth2AuthenticationEntryPoint? (I have included a reference link in the code to the inspiration for my version.) for errors that throws a JwtValidationException ?

1

There are 1 answers

1
Plaul On

I finally found the problem which comes from the way I originally set the CustomOAuth2AuthenticationEntryPoint.

If I replace the lines (given in the code for the question) with this:

            .authenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint())
            .accessDeniedHandler(new CustomOAuth2AccessDeniedHandler())

It works fine. I'm not sure how I got the original version, and also a bit strange the it worked for the CustomOAuth2AccessDeniedHandler but not CustomOAuth2AuthenticationEntryPoint?