Java Spring get attributes from Active Directory UserDetails

人盡茶涼 提交于 2019-12-02 12:24:37

You can implement your own user details mapper by extending springs ldap one.

package example.active.directory.authentication;

import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;

public class CustomUserMapper extends LdapUserDetailsMapper{

    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities){

        UserDetails details = super.mapUserFromContext(ctx, username, authorities);
        String[] changedValues = ctx.getStringAttributes("whenchanged");
        /// Do something here, like map to your custom UserDetails object.
        return details;        
    }
}

If you set a breakpoint in that method, you should be able to explore all the different attributes available to you in your debugger.

This is similar to another answer I gave: Update users informations during login against LDAP AD using Spring

First set your provider by adding below in your SecurityConfiguration. If not set, defaults to a simple LdapUserDetailsMapper which doesn't have all attributes.

provider.setUserDetailsContextMapper(userDetailsContextMapper());

@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
    ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(ldapdomain, ldapurl);
    provider.setConvertSubErrorCodesToExceptions(true);
    provider.setUseAuthenticationRequestCredentials(true);
    provider.setUserDetailsContextMapper(userDetailsContextMapper());
    return provider;
}

@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
     return new CustomUserMapper();
}

Then create a custom mapper extending LdapUserDetailsMapper

public class CustomUserMapper extends LdapUserDetailsMapper{

    @Override
    public CustomUserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities){

        // set from userDetails 
        UserDetails details = super.mapUserFromContext(ctx, username, authorities);

        // set directly from ctx 
        CustomUserDetails customUserDetails = new CustomUserDetails();
        customUserDetails.setFirstName(ctx.getStringAttribute("givenName"));
        customUserDetails.setLastName(ctx.getStringAttribute("sn"));

        return customUserDetails;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!