2010-11-08 62 views
0

问候所有 我使用下面的方法,使编程登录的用户,但与他的用户名&密码,并能正常工作:使程序登录没有用户名/密码?

public static void autoLogin(User user, HttpServletRequest request, 
    AuthenticationManager authenticationManager) { 

    GrantedAuthority[] grantedAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl(
    user.getAuthority()) }; 

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
    user.getUserName(), user.getPassword(), 
    grantedAuthorities); 

    // generate session if one doesn't exist 
    request.getSession(); 

    token.setDetails(new WebAuthenticationDetails(request)); 
    Authentication authenticatedUser = authenticationManager 
    .authenticate(token); 

    SecurityContextHolder.getContext().setAuthentication(authenticatedUser); 
    // setting role to the session 
    request 
    .getSession() 
    .setAttribute(
     HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, 
     SecurityContextHolder.getContext()); 

} 

,我想知道如果有可能使编程登录,但没有用户名或密码认证,只是让这个用户认证。

回答

0

设法做到这一点通过除去那些线token.setDetails除去那些线

token.setDetails(new WebAuthenticationDetails(request)); 
Authentication authenticatedUser = authenticationManager .authenticate(token); 
+1

如果您删除了这两行,那么以下行是如何编译的? 。SecurityContextHolder.getContext()setAuthentication(authenticatedUser); – 2012-11-22 03:37:11

1

您可以创建自己的子类Authentication,实施支持它的AuthenticationProvider并配置认证管理器以使用此提供程序。

(实际上,你可以简单地把一个自定义Authentication总是返回trueisAuthenticated()SecurityContext,但这种方法绕过AuthenticationManager,因此,例如,AuthenticationSuccessEvent将不会被发表)。

+0

设法做到这一点(新WebAuthenticationDetails(请求)); Authentication authenticatedUser = authenticationManager .authenticate(token); – 2010-11-09 08:52:07

相关问题