使用Spring LdapTemplate从Active Directory获取所有属性

时间:2018-03-21 07:43:40

标签: spring spring-boot active-directory ldap spring-ldap

我有一个Spring Boot应用程序,它使用LDAP对用户进行身份验证。对于用户,我将从AD映射属性并填充值,例如用户的名字,姓氏,部门,电子邮件,电话以及图像。但是,我无法从属性中获取员工编号。 当我使用工具Active Directory explorer检查属性时,我可以在每个条目中看到88个属性。但是,当我使用此代码打印上下文中的每个属性时,

@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
    return new LdapUserDetailsMapper() {
        @Override
        public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {

            String email = ctx.getStringAttribute("mail");
            String department = ctx.getStringAttribute("department");
            String empNumber = ctx.getStringAttribute("employeeNumber");
            System.out.println(empNumber); // this prints null

            System.out.println(ctx.attributeExists("employeeNumber")); // this prints false



            byte[] value= (byte[])ctx.getObjectAttribute("thumbNailPhoto");
            BASE64Encoder base64Encoder = new BASE64Encoder();
            StringBuilder imageString = new StringBuilder();
            imageString.append("data:image/jpg;base64,");
            imageString.append(base64Encoder.encode(value));
            String image = imageString.toString();

            Attributes attributes = ctx.getAttributes();

            NamingEnumeration<? extends Attribute> namingEnumeration = attributes.getAll();

            try {
                while(namingEnumeration.hasMore()){ 
                 /*this loop prints 75 attributes but employeeNumber attribute is missing along with some other attributes*/
                    Attribute attribute = namingEnumeration.next();
                    System.out.println(attribute); 
                }
            } catch (NamingException e) {
                e.printStackTrace();
            }

            CustomUserDetails userDetails = (CustomUserDetails)userService.loadUserByUsername(username);
            userDetails.setImage(image);
            userDetails.setEmail(email);
            userDetails.setDepartment(department);

            return userDetails;
        }
    };
}

仅打印75个属性。为什么没有检索到某些属性?我该如何访问这些属性?

1 个答案:

答案 0 :(得分:0)

我认为您需要扩展诸如memberof之类的数组元素。

尝试一下..可能有帮助。

Attribute attribute = namingEnumeration.next();
System.out.println(attribute); 
System.out.println(attribute.size()); 

如果尺寸大于1,请再次展开