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

时间:2014-08-22 05:23:06

标签: java spring-security

我需要以编程方式登录通过Facebook API验证的用户。原因是每个用户(例如购物车)都有多个项目关联,因此一旦使用Facebook API对用户进行身份验证,我需要使用spring安全性登录用户以便能够访问他/她的购物车。

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

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

从第一个例子开始: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) {

mycode的

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

2 个答案:

答案 0 :(得分:12)

不幸的是,在Spring安全性中似乎没有“完全”支持程序化登录。以下是我成功完成的方法:

@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()

基本相同

答案 1 :(得分:4)

此代码来自Grails' Spring Security Core -Plugin,它是在Apache 2.0许可下发布的。我添加了导入只是为了指出类型是什么。原作者是Burt Beckwith。

import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

...

public static void reauthenticate(final String username, final String password) {
    UserDetailsService userDetailsService = getBean("userDetailsService");
    UserCache userCache = getBean("userCache");

    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
            userDetails, password == null ? userDetails.getPassword() : password, userDetails.getAuthorities()));
    userCache.removeUserFromCache(username);
}

getBean -method仅提供应用程序上下文中的bean。