Spring MVC 3.1 如何在Custom Authentication Provider(实现了AuthenticationProvider)中访问HttpSession

Suy*_*rve 6 authentication spring-mvc

我的应用程序在身份验证过程中调用 Web 服务(如下面的代码所示)。

在这个过程中如何在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;
        }

    }
 }
Run Code Online (Sandbox Code Playgroud)

Suy*_*rve 5

在这个问题上花了很多心思之后,我能够使用以下解决方法来实现目标。在以下方法中获取会话确实不可行 public Authentication authenticate(Authenticationauthentication)

我创建了一个类

import java.security.Principal;

public class UserInfo implements Principal{

private String customerId;
private String accountNumber;
private String name;
}
Run Code Online (Sandbox Code Playgroud)

我想在会话中存储的信息(如 customerId、accountNumber 等),我将其保存在 userInfo 对象中。并且该对象被传递给 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);
Run Code Online (Sandbox Code Playgroud)

该信息可以在用户会话中使用以下方式轻松获得

(UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Run Code Online (Sandbox Code Playgroud)

我认为这是解决问题的一个足够好的方法。