title: How to login a user programmatically using Spring-security?
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Those who created a user object but did not explain how.</p>
  
  <p>From first example:<a href="https://stackoverflow.com/questions/7900994/programmatically-login-in-a-user-using-spring-security">this answer</a> </p>
  
  <pre><code>  Authentication auth = 
    new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
  </code></pre>
  
  <p>From second example: <a href="http://java.dzone.com/articles/java-web-application-security-2" rel="noreferrer">this one</a></p>
  
  <pre><code>  34.User details = new User(username);
    35.token.setDetails(details);
  </code></pre>
  
  <p>From third example: <a href="https://stackoverflow.com/questions/11313309/spring-security-programmatic-login-without-a-password">this one</a></p>
  
  <pre><code>  Authentication authentication = new UsernamePasswordAuthenticationToken(user, null,
    AuthorityUtils.createAuthorityList("ROLE_USER"));
  </code></pre>
  
  <p>Another <a href="https://stackoverflow.com/questions/18006137/how-can-i-programmatically-authenticate-user-with-spring-security-using-daoauthe">example is here</a>, 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.</p>
  
  <pre><code>protected void automatedLogin(String username, String password, HttpServletRequest request) {
  </code></pre>
  
  <p>MyCode</p>
  
  <pre><code>...
  if(isAuthenticatedByFB())
  {
      login(username);
      return "success";
  }
  else{
      return "failed";
  }
  </code></pre>