Spring Security:来自UserDetailsS​​ervice的自定义异常消息

时间:2013-07-03 04:22:44

标签: spring authentication spring-security

当用户尝试使用不正确的凭据登录或因某些原因禁用了用户时,我能够显示SPRING_SECURITY_LAST_EXCEPTION.message(“错误的凭据”)。

我想为用户被禁用的情况显示自定义消息,而不是显示“Bad Credentials”而是显示“您已被禁用...等等,等等......”。我该怎么做?

我正在使用UserDetailsS​​ervice在spring security中提供用户名/密码。

2 个答案:

答案 0 :(得分:10)

您需要将AbstractUserDetailsAuthenticationProvider的hideUserNotFoundExceptions属性设置为false。 (这意味着此解决方案依赖于Spring Security代码,该代码可能在将来发生变化)。

以下是步骤:

(1)定义一个DaoAuthenticationProvider bean(如果已有),则将其hideUserNotFoundExceptions属性设置为false。这是Java配置样式:

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

(2)使用上述提供者配置身份验证管理器:

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

(3)创建扩展UsernameNotFoundException的例外:

    public class DisabledException extends UsernameNotFoundException {

    public DisabledException(String msg) {
    super(msg);
    }

    /* other constructors */    
}

(4)在您的UserDetailsS​​ervice中,使用您喜欢的任何消息键抛出上述异常:

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

此处消息为SpringSecurityMessageSource.getAccessor()

答案 1 :(得分:0)

在类路径中创建属性文件,如loginMessage.properties

在该属性文件中,指定

AbstractUserDetailsAuthenticationProvider.badCredentials =输入的用户名/密码不正确。

在applicationContext.xml中添加以下bean,

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

在userDao中,如果结果为null

throw new UsernameNotFoundException("");

之后,您将收到输入的用户名/密码错误消息。而不是坏证书