If you are trying to receive the user credentials via a REST Endpoint and manually authenticate the user you can do this way:
@RestController
@RequestMapping("/login")
public class LoginController {
private final AuthenticationManager authenticationManager;
// constructor injecting authenticationManager
@PostMapping
public void login(@RequestBody UserCredentials credentials) {
UsernamePasswordAuthenticationToken token
= new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
Authentication auth = this.authenticationManager.authenticate(token);
if (auth != null) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(auth);
SecurityContextHolder.setContext(context);
}
throw new SomeException();
}
}
This way, the Filters
will take care of the rest of the authentication steps for you. The Spring Security documentation can be researched for more details.
If you want to use the endpoint generated with the default login page, you can follow the steps from the documentation to make your own request:
- The form should perform a post to /login
- The form will need to
include a CSRF Token which is automatically included by Thymeleaf.
- The form should specify the username in a parameter named username
- The form should specify the password in a parameter named password
- If the HTTP parameter error is found, it indicates the user failed to
provide a valid username / password
- If the HTTP parameter logout is
found, it indicates the user has logged out successfully