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
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With