The Spring Security module supports by default some standard ways to retrieve user information for authentication from databases, LDAP or other commonly used storages. But unfortunately the Spring documentation does not say much about creating connections to custom data sources. There are actually several different ways to do it.
But let’s say we have a Spring MVC application with a login form which contains a user name and password field, but the application does not use any of the supported methods to store the user data. How can we authenticate the user anyway?
The easiest way in my opinion is to create a new authentication provider. So we simply need to implement the AuthenticationProvider
interface.
The authenticate()
function of the class must return an UsernamePasswordAuthenticationToken
instance if the authentication is successful or null
otherwise. You can choose another token, simple check the classes implementing AbstractAuthenticationToken
. But for our scenario this should be enough.
It is important to populate the list of authorities we grant the user. I used the standard user role (“ROLE_USER
”).
In the real-world you might want to add a member variable to the authentication provider pointing to a bean which contains the code for authenticating an user, here I just hard-coded it (name must be “admin”, password “system”).
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
if (name.equals("admin") && password.equals("system")) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
return auth;
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
Now we need to declare the new authentication provider in our configuration:
<authentication-manager>
<authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>
And that’s it!