Programatically Login in Spring

api-client-authentication

You need this in various scenarios, for example at sign up. You can do it as follows:

...
@Autowired
private AuthenticationManager authenticationManager;

private void doLogin(String username, String password,
    HttpServletRequest request) {

  try {
    // Must be called from request filtered by Spring Security, otherwise
    // SecurityContextHolder is not updated
    UsernamePasswordAuthenticationToken token;
    token = new UsernamePasswordAuthenticationToken(username,password);
    token.setDetails(new WebAuthenticationDetails(request));

    Authentication authentication;
    authentication = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
  } catch (Exception e) {
    SecurityContextHolder.getContext().setAuthentication(null);
  }
}
...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s