【问题标题】:How to get custom User object from AuthenticationFailureBadCredentialsEvent / AuthenticationSuccessEvent object如何从 AuthenticationFailureBadCredentialsEvent / AuthenticationSuccessEvent 对象获取自定义用户对象
【发布时间】:2013-04-29 09:39:27
【问题描述】:

我正在尝试显示没有使用 spring security 的用户的无效尝试。我正在使用自定义 User 类来获取除用户名和密码之外的其他用户详细信息。我创建了两个侦听器类,即 AuthenticationSuccessEventListener 和 AuthenticationFailureListener 来更新用户的无效尝试。

现在在 onApplicationEvent 方法中,我正在尝试获取自定义用户对象 (CustomUserDetails),如下所示:

    @Component
    public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
        @Autowired
        private ILoginDAO loginDAO ;            
        @Override
        public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
            CustomUserDetails user = (CustomUserDetails)event.getAuthentication().getPrincipal();//I get ClassCastException here.
            String strUserID = user.getUserID();
            CustomUserDetails customUser = loginDAO.loadUserByUsername(strUserID);
            if (customUser != null){
        ...
       } } }

event.getAuthentication().getPrincipal() 返回一个字符串,即我试图将其转换为 CustomUserDetails(自定义用户类)的用户名,我得到错误。

P.S - 我在登录页面中输入用户 ID/密码,因此我将用户 ID 作为参数传递给所有方法,包括 loadUserByUsername(strUserID)。

如何从 AuthenticationFailureBadCredentialsEvent / AuthenticationSuccessEvent 对象中获取我的自定义用户对象?

【问题讨论】:

    标签: spring spring-security spring-webflow


    【解决方案1】:

    该事件仅包含身份验证请求对象,即传递给AuthenticationManager 并失败的Authentication。所以它将包含提交的用户名作为主体。

    身份验证可能由于多种原因而失败,包括不存在的用户名,实际上甚至根本不需要涉及 UserDetails 对象,因此如果您想要完整的信息,您需要加载它使用用户名。

    或者,您可以自定义 AuthenticationProvider 以在实现本身中执行您想要的额外工作,而不是通过事件。

    【讨论】:

    • 卢克感谢您的回复。关于第一种方法,我有一个问题。在我的 D/B 登录表中,“用户 ID”是主键,“用户名”不是唯一的,不同用户可以相同。因此在登录页面中,用户输入“用户 ID”而不是“用户名”。在这种情况下,如何使用“用户名”从 D/B 中选择匹配记录?
    • 该值应该是用户在登录表单中输入的任何内容 - 即 Spring Security 所称的“用户名”。如果你称它为“userId”,这并不重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2021-05-10
    相关资源
    最近更新 更多