Reputation: 1860
I'm trying to create a login page which returns a JWT if the login is successful but I can't understand how some functionalities work. I'm currently following a nice tutorial for JWT authentication where the author creates a "/login" endpoint which looks like :
@PostMapping("/login")
public String login(@RequestBody LoginUserDto loginUser) {
try{
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(//email,//password));
}catch(BadCredentialsException exception) {....}
final UserDetails userDetails = userDetailsService.loadUserByUsername(//email);
return createToken(userDetails.getUsername());
}
Why is he still calling userDetailsService.loadUserByUsername()
if the authenticate()
method doesn't throw any BadCredentialsException
?
Anyway, I've seen that this userDetailsService
is configured inside a WebSecurityConfigurerAdapter
class:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
But again, what is the purpose of this UserDetailsService
if he uses the AuthenticationManager
? Because I've seen in almost every tutorial that I need to implement this interface...
Upvotes: 1
Views: 1710
Reputation: 1728
The UserDetailsService
is used to load the user from a back-end structure like database. The loadUserByUsername
method is called when a user tries to login with a username and password. The method loadUserByUsername
returns an UserDetails
object where you can get the user’s authentication and authorization information (more specific information from you domain user, like: employee number, full name) . So, you may need it for a more detailed usage during application flow, like getting to know if the user full name adhere to a logic. Calling authenticationManager.authenticate
you get to check the credentials against the provider (LDAP, Database, OAUTH and etc).
Creating a custom UserDetailsService
object is an easy mechanism that allows for Spring Security to make security decisions based on your custom domain model. Spring Security requires UserDetailsService
in order to use the built-in remember-me support and UserDetailsService
object does not work when authentication is not based on a username and password.
Upvotes: 3