How to login a user programmatically using Spring-security?

梦想的初衷 提交于 2020-01-10 14:11:51

问题


I need to programmatically login users that were authenticated through Facebook API. The reason for that is that there are number of items that are associated to each user (for example shopping cart), therefore once user is authenticated using Facebook API, I need to log the user in using spring security as well to be able to access his/her shopping cart.

Based on my research, there are many methods to implement it but I could not deploy any of them as I am sending log-in request from my code, also another problem is that some people created user object but they did not explain how to create it.

Those who created a user object but did not explain how.

From first example:this answer

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

From second example: this one

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

From third example: this one

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

Another example is here, it does not help because I need to log-in user from my own code not from browser; therefore I do not know how to populate HttpServletRequest object.

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

MyCode

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

回答1:


Unfortunately it seems there is no "complete" support of programmatic login in Spring security. Here is how I've done it successfully:

@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);
}

UPDATE Essentially the same is done by Spring's RememberMeAuthenticationFilter.doFilter()




回答2:


This code is from Grails' Spring Security Core -Plugin, which is released under the Apache 2.0 license. I've added the imports just to point out what the types are exactly. The original author is 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);
}

The getBean-method merely provides the bean from application context.



来源:https://stackoverflow.com/questions/25440059/how-to-login-a-user-programmatically-using-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!