I'm using LDAP authentication in spring-boot application (configuration based on annotations). I would like to customize UserDetails object. Default UserDetails implementation is LdapUserDetailsImpl. I would like to extend this class and add some extra iterfaces and bind into spring-security. My config class:
@Configuration
protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private Environment env;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
AuthMethod authMethod = AuthMethod.valueOf(env.getRequiredProperty("auth_method"));
switch (authMethod) {
case LDAP:
auth.ldapAuthentication()
.userDnPatterns(env.getRequiredProperty("ldap.user_dn_patterns"))
.groupSearchBase(env.getRequiredProperty("ldap.group_search_base"))
.contextSource()
.url(env.getRequiredProperty("ldap.url"));
break;
default:
auth.userDetailsService(userService);
break;
}
}
@Bean
public LdapContextSource contextSource () {
LdapContextSource contextSource= new LdapContextSource();
contextSource.setUrl(env.getRequiredProperty("ldap.url"));
contextSource.setUserDn(env.getRequiredProperty("ldap.user"));
contextSource.setPassword(env.getRequiredProperty("ldap.password"));
contextSource.afterPropertiesSet();
return contextSource;
}
}
UserService is custom method of authentication (it's database/jpa authentication). UserDetails accessor (when auth method is LDAP it's returning LdapUserDetailsImpl object):
@Component("activeUserAccessor")
public class ActiveUserAccessorImpl implements ActiveUserAccessor
{
public UserDetails getActiveUser()
{
return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
Thank you for your help.
My solution:
1.Create custom UserDetailsContextMapper:
2.Bind UserDetailsContextMapper with LdapAuthenticationProviderConfigurer:
3.Implement CustomLdapUserDetails (only isEnabled method is changed for now). You can add some extra interfaces, methods to CustomLdapUserDetails and return extended class in ActiveUserAccessor.getActiveUser().