This post will be continuing the security-series and we will get right into it by logging in with a user defined in our database.
Implementation
We'll connect to the database in the same way we saw in this post and we'll define the UserRepository and the User entity to retrieve user data.
UserDetailsService
In the previous post of this series we found that the UserDetailsService is Spring Security's component responsible with finding the user.
This is why, to do authentication based on database-stored users we need to implement our own custom UserDetailsService. This service will hold a reference to the UserRepository.
Because we implement the UserDetailsService we need to follow the loadUserByUsername method signature. This is the reason why we need to create our own CustomUserDetails to be returned as a result.
AuthenticationProvider
Next, the AuthenticationProvider is the component responsible with the actual authentication logic. Holding references to UserDetailsService and PasswordEncoder ( in our case CustomUserDetailsService and NoOpPasswordEncoder) we will create a CustomAuthenticationProvider.
Same as with the UserDetailsService, implementing the AuthenticationProvider interface forces us to follow a certain method signature for the authenticate method. It receives as an input and also returns as a result an Authentication object. For this example I chose the UsernamePasswordAuthenticationToken since we have a basic authorization based on user and password.
AuthenticationManager
The final thing we need to do is adding our CustomAuthenticationProvider to the Spring Security's AuthenticationManager.
Test
Bringing everything together, we'll test it sending a Postman request. You need to add a Basic Authorization on the request, having the username and password containing valid credentials from the database.
This post is the last one of the Authentication side of Spring Security. In the next posts we'll focus on Authorization. We'll define roles for our users and let them access endpoints in our application based on them.