In most cases when only using usernames and passwords for authentications and roles for authorisation, implementing your own UserDetailsService is enough.
The flow of the username password authentication is then generally as follows:
- A spring security filter (basic authentication/form/..) picks up the username and password, turns it into an UsernamePasswordAuthentication object and passes it on to the AuthenticationManager
- The authentication manager looks for a candidate provider which can handle UsernamePasswordtokens, which in this case is the DaoAuthenticationProvider and passes the token along for authentication
- The authentication provider invokes the method loadUserByUsername interface and throws either a UsernameNotFound exception if the user is not present or returns a UserDetails object, which contains a username, password and authorities.
- The Authentication provider then compares the passwords of the provided UsernamePasswordToken and UserDetails object. (it can also handle password hashes via PasswordEncoders) If it doesn't match then the authentication fails. If it matches it registers the user details object and passes it on to the AccessDecisionManager, which performs the Authorization part.
So if the verification in the DaoAuthenticationProvider suits your needs. Then you'll only have to implement your own UserDetailsService and tweak the verification of the DaoAuthenticationProvider.
An example for the UserDetailsService using spring 3.1 is as follows:
Spring XML:
<security:authentication-manager>
<security:authentication-provider user-service-ref="myUserDetailsService" />
</security:authentication-manager>
<bean name="myUserDetailsService" class="x.y.MyUserDetailsService" />
UserDetailsService Implementation:
public MyUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//Retrieve the user from wherever you store it, e.g. a database
MyUserClass user = ...;
if (user == null) {
throw new UsernameNotFoundException("Invalid username/password.");
}
Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("Role1","role2","role3");
return new User(user.getUsername(), user.getPassword(), authorities);
}
}