Spring Security: Custom exception message from UserDetailsService

霸气de小男生 提交于 2021-02-06 10:44:33

问题


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.

I want to display a custom message for the case where the user is disabled, not show "Bad Credentials" instead say "You have been disabled...blah,blah...". How do I do that?

I am using UserDetailsService for providing username/password in spring security.


回答1:


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:

<authentication-manager alias="authenticationManager">
    <authentication-provider ref="daoAuthenticationProvider"/>
<!-- other providers if any -->
</authentication-manager>

(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()




回答2:


Create a property file in class path like loginMessage.properties

In that property file, specify

AbstractUserDetailsAuthenticationProvider.badCredentials=Username/Password entered is incorrect.

Add the following bean in your applicationContext.xml,

<bean id="messageSource"   
    class="org.springframework.context.support.ResourceBundleMessageSource">  
    <property name="basenames">  
        <list>
            <value>loginMessage</value>
        </list>
    </property>
</bean>

In userDao, if result null

throw new UsernameNotFoundException("");

After that, u'll get message like Username/Password entered is incorrect. instead of Bad Credentials



来源:https://stackoverflow.com/questions/17439628/spring-security-custom-exception-message-from-userdetailsservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!