Spring Security: Custom exception message from UserDetailsService

后端 未结 2 1045
一生所求
一生所求 2021-02-08 13:59

I am able to display the SPRING_SECURITY_LAST_EXCEPTION.message (\"Bad Credentials\") when a user tries to log in with incorrect credentials or user is disabled for some reason.

2条回答
  •  没有蜡笔的小新
    2021-02-08 14:15

    You need to set hideUserNotFoundExceptions property of AbstractUserDetailsAuthenticationProvider to false. (This means this solution is dependent on the Spring Security code which might change in the future).

    Here are the steps:

    (1) Define a DaoAuthenticationProvider bean (if you already have one then set its hideUserNotFoundExceptions property to false). Here is Java config style:

        @Bean
    public AuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider impl = new DaoAuthenticationProvider();
        impl.setUserDetailsService(yourUserDetailsService());
        impl.setHideUserNotFoundExceptions(false) ;
        return impl ;
    }
    

    (2) Configure authentication manager with above provider:

    
        
    
    
    

    (3) Create an exception extending the UsernameNotFoundException:

        public class DisabledException extends UsernameNotFoundException {
    
        public DisabledException(String msg) {
        super(msg);
        }
    
        /* other constructors */    
    }
    

    (4) In your UserDetailsService, throw the above exception with any message key you like:

        throw new DisabledException(messages.getMessage(
                            "AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
    

    Here messages is SpringSecurityMessageSource.getAccessor()

提交回复
热议问题