2011-11-30 440 views
3

我有一个客户类,其中包含所有帐户信息(它不扩展Spring的userdetails.User类) 我试图在成功登录后执行一些操作(例如设置新的最后登录时间)。为了达到这个目的,我设置了一个自定义AuthenticationSuccessHandlerSpring Security - 身份验证用户名在AuthenticationSuccessHandler中为空

onAuthenticationSuccess方法中,我尝试从Authentication对象获取用户名。但是,此对象是User对象。如果我尝试从它得到username,我会得到空。 我能以某种方式设法使Authority对象成为Customer对象吗?或者,我的客户类是否必须扩展用户类?

更新

更多的细节:

我有我的User类。它是完全自行编写的,不实现或扩展任何接口/类。我没有实现UserDetailsS​​ervice的类。我applicationContext-security.xml<form-login>部分看起来是这样的:

<form-login login-page="/index.htm" 
       authentication-success-handler-ref='authSuccHandler' 
       authentication-failure-handler-ref='authFailureHandler' 
       default-target-url='/library/login.htm' 
       always-use-default-target='true'/> 

Theh authSuccHandler看起来是这样的:(必要的bean定义到位)

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()); //NullPointerException 
      super.onAuthenticationSuccess(request, response, authentication); 
     } 
} 

形式重定向到j_spring_security_check

+0

能否请你加上你做什么具体配置,是非标准(例如UserDetailsS​​ervice中,自定义过滤器,认证提供商等)的更多细节。要弄清楚你已经定制了什么,以及你如何覆盖默认的Spring Security实现类,这有点难。另外,请让我们知道您使用的是什么版本。 –

+0

增加了一些细节。 – tschaei

回答

0

我认为您正在寻找的方法是getPrincipal on Authentication。然后,您必须对返回到您的自定义类的对象进行处理。

User user = (User)authentication.getPrincipal(); 
1

Authentication不能为User,因为它们不会相互继承。

如果您的UserDetailsService产生自定义UserDetails,您应该能够通过拨打Authentication调用getDetails()来获得它。

+0

我仍然无法使它工作。认证的getDetails()我的Customer类实现UserDetails,但我还是得到一个ClassCastException。如果我使用Authentication的getPrincipal(),则返回的对象的类型为User,用户名为null。我在这里错过了什么? – tschaei

1

当请求进入验证成功处理程序,它希望用户能够重定向到所需URL。使用以下命令重定向到所需页面,如home.htm。 这将工作肯定! 修改后的代码如下。检查它并让我知道你是否有任何问题。

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()); //NullPointerException 
     response.sendRedirect("home.htm"); 
     //super.onAuthenticationSuccess(request, response, authentication); 
    } 
} 
相关问题