Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security - Programmatic login without a password

I am trying to perform an automatic login when the user clicks a link in their email with Spring Security.

I have seen a lot of examples to perform a programmatic login like the following:

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
try {
    Authentication auth = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(auth);
    repository.saveContext(SecurityContextHolder.getContext(), request, response);
    rememberMeServices.loginSuccess(request, response, auth);
 ....

The problem I see is that I do not have the original password so I can't create a UsernamePasswordAuthenticationToken. Any other way to login the user if I do not have the plain text password (I have the one that is encoded)?

Thanks in advance.

like image 349
Agustin Lopez Avatar asked Jul 03 '12 14:07

Agustin Lopez


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.

How does Spring Security authentication work internally?

The Spring Security Architecture There are multiple filters in spring security out of which one is the Authentication Filter, which initiates the process of authentication. Once the request passes through the authentication filter, the credentials of the user are stored in the Authentication object.


1 Answers

Be careful that you know what you are doing in terms of allowing login from a link within an email. SMTP is not a secure protocol and so it is typically bad to rely on someone having an email as a form of authentication.

You do not need to use the AuthenticationManager if you already know they are authenticated. Instead you can just set the Authentication directly as shown below:

Authentication authentication = new UsernamePasswordAuthenticationToken(user, null,
    AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(authentication);

If you want a complete example, you can refer to the SignupController in the secure mail application that was the basis for Getting Started with Spring Security 3.1 (InfoQ video of presentation).

like image 123
Rob Winch Avatar answered Oct 17 '22 03:10

Rob Winch