I\'m using LDAP authentication in spring-boot application (configuration based on annotations). I would like to customize UserDetails object. Default UserDetails implementat
My solution:
1.Create custom UserDetailsContextMapper:
@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
return new LdapUserDetailsMapper() {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
UserDetails details = super.mapUserFromContext(ctx, username, authorities);
return new CustomLdapUserDetails((LdapUserDetails) details, env);
}
};
}
2.Bind UserDetailsContextMapper with LdapAuthenticationProviderConfigurer:
auth.ldapAuthentication()
.userDetailsContextMapper(userDetailsContextMapper())
.userDnPatterns(env.getRequiredProperty("ldap.user_dn_patterns"))
.groupSearchBase(env.getRequiredProperty("ldap.group_search_base"))
.contextSource()
.url(env.getRequiredProperty("ldap.url"));
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().
public class CustomLdapUserDetails implements LdapUserDetails {
private static final long serialVersionUID = 1L;
private LdapUserDetails details;
private Environment env;
public CustomLdapUserDetails(LdapUserDetails details, Environment env) {
this.details = details;
this.env = env;
}
public boolean isEnabled() {
return details.isEnabled() && getUsername().equals(env.getRequiredProperty("ldap.username"));
}
public String getDn() {
return details.getDn();
}
public Collection<? extends GrantedAuthority> getAuthorities() {
return details.getAuthorities();
}
public String getPassword() {
return details.getPassword();
}
public String getUsername() {
return details.getUsername();
}
public boolean isAccountNonExpired() {
return details.isAccountNonExpired();
}
public boolean isAccountNonLocked() {
return details.isAccountNonLocked();
}
public boolean isCredentialsNonExpired() {
return details.isCredentialsNonExpired();
}
}