authentication - Spring MVC 3.1 如何在自定义身份验证提供程序(实现 AuthenticationProvider)中访问 HttpSession

标签 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;
        }

    }
 }

最佳答案

在这个问题上打破了很多头之后,我能够使用以下解决方法实现目标。
在以下方法中获取 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/

相关文章:

python - Django 登录/有效负载在 Chrome DevTools 中以明文形式可见

java - 通过 Spring Controller 映射图像文件

android - 使用 AndroidAnnotations (Spring Rest) 处理超时

arrays - Spring MVC + RequestParam 作为 Map + 获取 URL 数组参数不起作用

javascript - JWT token 和 Handlebars 。保存到本地存储

rest - 如何使用 REST API 获取身份验证 token 或登录 Elastic Search?例如来自 postman

c# - 在 C# 中使用 Windows 用户名密码

java - spring mvc框架中业务逻辑放在哪里?

javascript - 如何验证Spring表单:form's form:password with JQuery Validation?

php - 使用 laravel 检查事件用户状态