2012-07-06 69 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); 

此信息在用户的会话一应俱全。