Programatically Login in Spring


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

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);
  } catch (Exception e) {

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s