Skip to content
Advertisement

How to handle UsernameNotFoundException spring security

How to handle UsernameNotFoundException ?

In spring security when username not found the UserDetailsService implementation throws a UsernameNotFoundException. For example like this:

JavaScript

I would like to build a custom “User not found REST response”. How should I catch/handle this exception? I have implemented a handler method in the WebSecurityConfigurerAdapter implementation the handler:

JavaScript

But this method should wait for an AuthenticationException exception which, and during runtime the type of the exception is java.lang.NullPointerException so I’m not able to cast or retrieve the the initial UsernameNotFoundException.

Any advice would be appreciated. Many many regards :).

Advertisement

Answer

Security layer comes before anything in the controllers and @ControllerAdvice. Hence @ControllerAdvice isn’t an option since UsernameNotFoundException which is a subclass of AuthenticationException is thrown during authenticaton, making your exception handlers in @ControllerAdvice unreachable.

You can only use @ControllerAdvice and ResponseEntityExceptionHandler if you are throwing UsernameNotFoundException inside controller or any others beans referenced from the controllers.

Here is my suggestion – that you implement AuthenticationFailureHandler and use it with AuthenticationFilter that you are using for your security configuration. Spring boot security comes with about 4 handler interfaces for security related issues

  1. AccessDeniedHandler – this handles issues like when a user not having required roles.
  2. AuthenticationEntryPoint – this handles issues like when a user tries to access a resource without appropriate authentication elements.

  3. AuthenticationFailureHandler – this handles issues like when a user is not found(i.e. UsernameNotFoundException) or other exceptions thrown inside authentication provider. In fact, this handles other authentication exceptions that are not handled by AccessDeniedException and AuthenticationEntryPoint.

  4. AuthenticationSuccessHandler – this helps to do stuff like redirection after a user is successfully authenticated.

See the following example snippets for the implementation of all the 4 interfaces. Please customize these to your taste.

  1. AccessDeniedHandler implementation
JavaScript
  1. AuthenticationEntryPoint Implementation
JavaScript
  1. AuthenticationFailureHandler implementation
JavaScript
  1. AuthenticationSuccessHandler implementation
JavaScript

This is the Security configuration that extends WebSecurityConfigurerAdapter that connects everything together.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement