2010-11-08 72 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

相關問題