Spring Security: Handle InvalidBearerTokenException in @ExceptionHandler

Viewed 988

When user passes an invalid JWT token, I see in the logs that InvalidBearerTokenException is being raised

org.springframework.security.oauth2.server.resource.InvalidBearerTokenException: An error occurred while attempting to decode the Jwt: Invalid JWT serialization: Missing dot delimiter(s)
    at org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider.getJwt(JwtAuthenticationProvider.java:101) ~[spring-security-oauth2-resource-server-5.4.5.jar:5.4.5]
    at org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider.authenticate(JwtAuthenticationProvider.java:88) ~[spring-security-oauth2-resource-server-5.4.5.jar:5.4.5]

I already have exception handling workflow for Spring Security which works like below

    @ExceptionHandler(value = InvalidBearerTokenException.class)
    public ResponseEntity<ErrorDto> handleInvalidBearerTokenException(InvalidBearerTokenException invalidBearerTokenException) {
        logger.error("Access denied for given token", invalidBearerTokenException);
        ErrorDto errorResponseDTO = new ErrorDto();
        errorResponseDTO.setMessage(invalidBearerTokenException.getMessage());

        return new ResponseEntity<>(errorResponseDTO, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<ErrorDto> handleAccessDeniedException(AuthenticationException authenticationException) {
        logger.error("Access denied for given token", authenticationException);
        ErrorDto errorResponseDTO = new ErrorDto();
        errorResponseDTO.setMessage(authenticationException.getMessage());

        return new ResponseEntity<>(errorResponseDTO, HttpStatus.UNAUTHORIZED);
    }
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException)
        throws ServletException, IOException {

        resolver.resolveException(request, response, null, authenticationException);

    }
}
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    protected void configure(HttpSecurity http) throws Exception {
        http
            .exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and()
        ...
    }
}

Though the rest of the authentication exceptions are being caught in exception handler except InvalidBearerTokenException. What am I missing?

0 Answers
Related