Spring security switch to Ldap authentication and database authorities
You need to create a CustomAuthenticationProvider wich implements AuthenticationProvider, and override authenticate method, for example:
@Component
public class CustomAuthenticationProvider
implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
boolean authenticated = false;
/**
* Here implements the LDAP authentication
* and return authenticated for example
*/
if (authenticated) {
String usernameInDB = "";
/**
* Here look for username in your database!
*
*/
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
Authentication auth = new UsernamePasswordAuthenticationToken(usernameInDB, password, grantedAuths);
return auth;
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
Then, in your SecurityConfig, you need to override the configure thats use AuthenticationManagerBuilder:
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this.authenticationProvider);
}
You can autowire the CustomAuthenticationProvider doing this:
@Autowired
private CustomAuthenticationProvider authenticationProvider;
Doing this, you can override the default authentication behaviour.
Spring Security already supports LDAP out-of-the-box. It actually has a whole chapter on this.
To use and configure LDAP add the spring-security-ldap
dependency and next use the AuthenticationManagerBuilder.ldapAuthentication
to configure it. The LdapAuthenticationProviderConfigurer
allows you to set the needed things up.
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.contextSource()
.url(...)
.port(...)
.managerDn(...)
.managerPassword(...)
.and()
.passwordEncoder(passwordEncoder())
.userSearchBase(...)
.ldapAuthoritiesPopulator(new UserServiceLdapAuthoritiesPopulater(this.userService));
}
Something like that (it should give you at least an idea on what/how to configure things) there are more options but check the javadocs for that. If you cannot use the UserService
as is to retrieve the roles (because only the roles are in the database) then implement your own LdapAuthoritiesPopulator
for that.