Spring Security - 在没有UserDetails / UserDetailsS​​ervice的AuthenticationSuccessHandler中获取用户名

时间:2011-12-18 15:43:44

标签: authentication spring-security

我正在尝试在自定义AuthenticationSuccessHandler中为用户设置LastLogin时间,但我不知道检索用户名的方法(因为所有权限函数似乎都返回null,因为我没有使用的UserDetails)。 用户数据存储在MYSQL表中,我使用Hibernate来检索/创建/更新用户。在我的应用程序中,我使用的是自编写的User类,它与Spring User类没有任何关系。我没有任何自定义UserDetails / UserDetailsS​​ervice,我想避免它们,因为我无法更改数据库表格布局(如添加其他值)

AuthenticationSuccessHandler如下所示:

public class PostSuccessfulAuthenticationHandler extends SimpleUrlAuthenticationSuccessHandler {
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException 
        {
            userService.trackUserLogin(authentication.getName()); //Doesn't work, getName seems to return null
            super.onAuthenticationSuccess(request, response, authentication);
        }
}

我的applicationContext-security.xml如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

<global-method-security pre-post-annotations="enabled"/>
<!-- authentication-success-handler-ref='authSuccHandler' -->
<http use-expressions="true" disable-url-rewriting="true">
    <intercept-url pattern="..." access="hasRole('ROLE_USER')" />
    <form-login login-page="/index.htm"
                authentication-failure-handler-ref='authFailureHandler'
                authentication-success-handler-ref='authSuccHandler'
                default-target-url='...'
                always-use-default-target='true'/>
    <logout logout-success-url="..."/>
    <session-management invalid-session-url="/index.htm">
        <concurrency-control max-sessions="2" error-if-maximum-exceeded="true" />
    </session-management>
</http>

<authentication-manager>
    <authentication-provider>
        <jdbc-user-service data-source-ref="mysqldataSource" 
                    authorities-by-username-query="select username, authority from benutzer where username = ?"
                    users-by-username-query="select username, password, enabled from benutzer where username = ?"/>
    </authentication-provider>
</authentication-manager>

</beans:beans>

登录本身工作正常(即使我只在我的AuthenticationSuccessHandler中注释掉trackUserLogin行),这让我相信必须有一种获取该用户名的方法。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:4)

尝试authentication.getPrincipal()