我需要以编程方式登录通过 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/