2012-07-06 71 views
4

我的應用程序在身份驗證過程中調用Web服務(如下面的代碼所示)。Spring MVC 3.1如何在自定義身份驗證提供程序(實現AuthenticationProvider)中訪問HttpSession

在這個過程中,我如何在HttpSession中保存一些信息? 用戶登錄後,客戶賬號等信息將在應用程序的各個地方使用。 是否可以將HttpSession參數傳遞給MyServiceManager的靜態登錄方法?

public class MyAuthenticationManager implements AuthenticationProvider { 

    @Override 
    public boolean supports(Class<? extends Object> authentication) { 
     return authentication.equals(UsernamePasswordAuthenticationToken.class); 
    } 

    @Override 
    public Authentication authenticate(Authentication authentication) { 
        //MyServiceManager.login - makes a call to web service 
     if(MyServiceManager.login(authentication.getName(),  authentication.getCredentials().toString(), XXX_HTTP_SESSION_XXX)) 
     { 
      List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority> (); 
      authorities.add(new GrantedAuthorityImpl("ROLE_USER")); 
      authorities.add(new GrantedAuthorityImpl("ROLE_SUPERVISOR")); 
      return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(),authorities); 
     } 
     else 
     { 
      return null; 
     } 

    } 
} 

回答

3

在這個問題上突破了很多頭後,我用以下工作實現了目標。 獲取會議的持有是真的不

我創建了一個類

import java.security.Principal; 

public class UserInfo implements Principal{ 

private String customerId; 
private String accountNumber; 
private String name; 
} 

,我想在會話存儲(資料在下面的方法 認證公開身份驗證(驗證認證)是可行的像客戶ID,使用accountNumber等),我將它保存在userInfo對象中。 這個對象是通過使用

(UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 

我的家,這是一個足夠好的辦法來解決這個問題,以UsernamePasswordAuthenticationToken

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
authorities.add(new GrantedAuthorityImpl("ROLE_USER")); 
authorities.add(new GrantedAuthorityImpl("ROLE_SUPERVISOR")); 
return new UsernamePasswordAuthenticationToken(**userInfo**, authentication.getCredentials(),authorities); 

此信息在用戶的會話一應俱全。