java - 如何使用 Spring-security 以编程方式登录用户?

标签 java spring-security

我需要以编程方式登录通过 Facebook API 进行身份验证的用户。这样做的原因是有许多项目与每个用户相关联(例如购物车),因此一旦用户使用 Facebook API 进行身份验证,我还需要使用 spring security 登录用户才能访问他/她的购物车。

根据我的研究,有很多方法可以实现它,但我无法部署其中任何一个,因为我正在从我的代码发送登录请求,另一个问题是有些人创建了用户对象,但他们没有解释如何创建它。

那些创建了用户对象但没有解释如何创建的人。

来自第一个例子:this answer

  Authentication auth = 
  new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

来自第二个例子:this one

  34.User details = new User(username);
  35.token.setDetails(details);

来自第三个例子:this one

  Authentication authentication = new UsernamePasswordAuthenticationToken(user, null,
  AuthorityUtils.createAuthorityList("ROLE_USER"));

另一个example is here ,它没有帮助,因为我需要从我自己的代码而不是浏览器登录用户;因此我不知道如何填充 HttpServletRequest 对象。

protected void automatedLogin(String username, String password, HttpServletRequest request) {

我的代码

...
if(isAuthenticatedByFB())
{
    login(username);
    return "success";
}
else{
    return "failed";
}

最佳答案

不幸的是,Spring Security 中似乎没有对编程登录的“完整”支持。这是我成功完成的方法:

@Autowired AuthenticationSuccessHandler successHandler;
@Autowired AuthenticationManager authenticationManager;  
@Autowired AuthenticationFailureHandler failureHandler;

public void login(HttpServletRequest request, HttpServletResponse response, String username, String password) {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    token.setDetails(new WebAuthenticationDetails(request));//if request is needed during authentication
    Authentication auth;
    try {
        auth = authenticationManager.authenticate(token);
    } catch (AuthenticationException e) {
        //if failureHandler exists  
        try {
            failureHandler.onAuthenticationFailure(request, response, e);
        } catch (IOException | ServletException se) {
            //ignore
        }
        throw e;
    }
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);
    successHandler.onAuthenticationSuccess(request, response, auth);//if successHandler exists  
    //if user has a http session you need to save context in session for subsequent requests
    HttpSession session = request.getSession(true);
    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}

更新 Spring 的 RememberMeAuthenticationFilter.doFilter()

基本上完成了相同的操作

关于java - 如何使用 Spring-security 以编程方式登录用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25440059/

相关文章:

javascript - 为什么相同的按位计算在 Java 和 JavaScript 中会产生不同的结果?

spring - 覆盖 J_Spring_Security_Check

session - GRAILS:如何通过Spring Security核心插件获取当前登录用户的数量?

java - 如何创建具有关联值(如 Swift 枚举)的 Java 枚举?

java - SSL 与 WebSphere MQ 7

java - Spring Data JPA 的 @PersistenceConstructor 注释是否与 Hibernate 结合使用?

java - 如何在 Spring 注销前执行操作?

spring - 为什么我的 spring security 配置似乎拒绝有效的 csrf token

java - Spring Security部署错误

java - 启动时控制台中的 Apache Tomcat 异常