I have a custom AuthenticationProvider for getting authentication via LDAP and authorization via JDBC. It's running but I think it's not the best way.
My custom AuthenticationProvider
:
public class ADAuthenticationJDBCAuthorizationProvider implements AuthenticationProvider {
private final ActiveDirectoryLdapAuthenticationProvider adDelegate;
@Autowired
private UtilisateurService utilisateurService;
public ADAuthenticationJDBCAuthorizationProvider(ActiveDirectoryLdapAuthenticationProvider adDelegate) {
this.adDelegate = adDelegate;
}
@Override
public Authentication authenticate(Authentication authentication) {
final Authentication a = adDelegate.authenticate(authentication);
final String name = a.getName().toLowerCase();
// Load additional authorities and create an Authentication object
final Collection<GrantedAuthority> authorities = utilisateurService.loadRolesFromDatabase(name);
final boolean isActive = utilisateurService.isActive(name);
return new AbstractAuthenticationToken(authorities) {
@Override
public Object getCredentials() {
return a.getCredentials();
}
@Override
public Object getPrincipal() {
return a.getPrincipal();
}
@Override
public boolean isAuthenticated() {
return isActive && a.isAuthenticated();
}
@Override
public String getName() {
return name;
}
};
}
@Override
public boolean supports(Class<?> authentication) {
return adDelegate.supports(authentication);
}
}
My configuration file:
public class GlobalSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
@Value("${ldap.domain}")
private String DOMAIN;
@Value("${ldap.url}")
private String URL;
@Autowired
private JDBCUserDetailsService userDetailsService;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider()).userDetailsService(userDetailsService);
}
@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider
= new ActiveDirectoryLdapAuthenticationProvider(DOMAIN, URL);
adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true);
adAuthenticationProvider.setUseAuthenticationRequestCredentials(true);
ADAuthenticationJDBCAuthorizationProvider authenticationProvider = new ADAuthenticationJDBCAuthorizationProvider(adAuthenticationProvider);
return authenticationProvider;
}
}
The custom UserDetailsService
:
public class JDBCUserDetailsService implements UserDetailsService {
@Autowired
private UtilisateurService utilisateurService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final String name = username.toLowerCase();
Collection<GrantedAuthority> authorities = utilisateurService.loadRolesFromDatabase(name);
final boolean isActive = utilisateurService.isActive(name);
return new User(username, "", isActive, true, true, true, authorities);
}
}
Do you have any suggestion for a better solution?