Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto login with spring security

I have an application which uses spring-security. In my signup process, a new user entity gets persisted with the HASHED password, an email containing an activation token is the sent to the user. Clicking on this token directs the user to a UserActivationServlet which looks up the user by the token, activates the user and redirects them to the application. I would like to automatically log the user into the application and have included this method in my servlet to do this

    private void authenticateUserAndSetSession(HttpServletRequest request, User u) {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            u.getUsername(), u.getPassword()); //PROBLEM: THIS PASSWORD IS HASHED

    // generate session if one doesn't exist
    request.getSession();

    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
}

The problem here is that that the password field on the User entity has been hashed when it was created. So the only other option I can think of is to pass the unhashed password as a request parameter to the servelet (nasty!)

Have I missed something, is there another way of pre-authenticating the user?

Thanks

like image 587
Clinton Bosch Avatar asked Jul 05 '11 10:07

Clinton Bosch


People also ask

Does Spring Security use default login form?

Spring security secures all HTTP endpoints by default. A user has to login in a default HTTP form. To enable Spring Boot security, we add spring-boot-starter-security to the dependencies.


1 Answers

The user has clicked on the activation link and we have looked him up so clearly we have a valid user, so there is no need to re-authenticate him with the authenticationManager and so no need to use credentials when creating the Token, just create it as follows:

PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( p, null, p.getAuthorities());
like image 63
Clinton Bosch Avatar answered Oct 03 '22 20:10

Clinton Bosch