我的应用程序在身份验证过程中调用 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;
}
}
}
最佳答案
在这个问题上打破了很多头之后,我能够使用以下解决方法实现目标。
在以下方法中获取 session 确实不可行
public Authentication认证(认证认证)
我创建了一个类
import java.security.Principal;
public class UserInfo implements Principal{
private String customerId;
private String accountNumber;
private String name;
}
我想在 session 中存储的信息(如 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);
此信息可在用户 session 中使用
(UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
我回家这是一个足够好的方法来解决这个问题。
关于authentication - Spring MVC 3.1 如何在自定义身份验证提供程序(实现 AuthenticationProvider)中访问 HttpSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11359234/