If you are implementing your own AuthenticationProvider, You don’t have to implement a UserDetailsService if you don’t want to. UserDetailsService just provides a standard DAO for loading user information and some other classes within the framework are implemented to use it.
Normally, to authenticate using a username and password, you would instantiate a DaoAuthenticationProvider and inject that with a UserDetailsService. That may still be your best approach. If you implement your own provider, you take on the responsibility of making sure the user has supplied the correct password and so on. However, in some cases this is a simpler approach.
To answer your “what should happen here?” comment in your code, it would be something like
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
String username = String.valueOf(auth.getPrincipal());
String password = String.valueOf(auth.getCredentials());
logger.info("username:" + username);
logger.info("password:" + password); // Don't log passwords in real app
// 1. Use the username to load the data for the user, including authorities and password.
YourUser user = ....
// 2. Check the passwords match (should use a hashed password here).
if (!user.getPassword().equals(password)) {
throw new BadCredentialsException("Bad Credentials");
}
// 3. Preferably clear the password in the user object before storing in authentication object
user.clearPassword();
// 4. Return an authenticated token, containing user data and authorities
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()) ;
}
The user object will then be accessible using the
Authentication.getPrincipal()
method, and you can access the additional properties (email etc) by casting it to your custom user implementation.
How you load the user data is up to you. All Spring Security cares about here is the AuthenticationProvider interface.
You should also store hashed passwords and validate the supplied password using the same algorithm, rather than a simple equality check.