How to login a user programmatically using Spring-security?

10,750

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

Solution 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.

Share:
10,750

Related videos on Youtube

Jack
Author by

Jack

Updated on October 18, 2022

Comments

  • Jack
    Jack over 1 year

    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";
    }
    
  • Jack
    Jack over 7 years
    Thanks, would you please elaborate further. do I need any requestHandler for it? How to configure the project?
  • Roman Sinyakov
    Roman Sinyakov over 7 years
    I use the typical spring security configuration which is applied in processing HTTP requests as usual. Code above works in special cases when I need to authenticate the user internally.
  • gstackoverflow
    gstackoverflow almost 7 years
    How to authtecicate using oauth 2.0 ?
  • Jay Edwards
    Jay Edwards about 6 years
    Please, where/how are you defining the securityContext variable supplied to session.setAttribute(...)?
  • Roman Sinyakov
    Roman Sinyakov about 6 years
    @JayEdwards thanks for the question, I fixed the code snippet
  • Madbreaks
    Madbreaks over 5 years
    The last two lines of that method (at least) are not thread safe. Instead do: request.getSession(true).setAttribute("SPRING_SECURITY_CONTE‌​XT", securityContext);
  • Tobias Hagenbeek
    Tobias Hagenbeek over 4 years
    so this actaully validates all passwords as true, even badones.