Spring Security:来自UserDetailsS​​ervice的自定义异常消息 [英] Spring Security: Custom exception message from UserDetailsService

查看:132
本文介绍了Spring Security:来自UserDetailsS​​ervice的自定义异常消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户尝试使用不正确的凭据登录或由于某种原因而被禁用时,我能够显示SPRING_SECURITY_LAST_EXCEPTION.message(错误凭据").

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?

我正在使用UserDetailsS​​ervice在Spring Security中提供用户名/密码.

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

推荐答案

您需要设置AbstractUserDetailsAuthenticationProvider 设置为false.(这意味着该解决方案取决于将来可能会更改的Spring Security代码.)

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

以下是步骤:

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

(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)使用上述提供程序配置身份验证管理器:

(2) Configure authentication manager with above provider:

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

(3)创建一个扩展(4)在您的UserDetailsS​​ervice中,使用您喜欢的任何消息键引发上述异常:

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

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

这里的消息是 SpringSecurityMessageSource.getAccessor()

这篇关于Spring Security:来自UserDetailsS​​ervice的自定义异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆