首页 > 解决方案 > 获取经过身份验证的 ldap 用户的 CN 条目

问题描述

我正在使用 Spring Boot 在 LDAP 上迈出第一步。我已经设法验证了我的 ldif 文件中列出的用户:

dn: dc=parascus,dc=de
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: parascus

dn: ou=groups,dc=parascus,dc=de
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=people,dc=parascus,dc=de
objectclass: top
objectclass: organizationalUnit
ou: people

dn: uid=jsmith,ou=people,dc=parascus,dc=de
objectclass: top
objectclass: person
objectclass: inetOrgPerson
cn: Smith, John
sn: Smith
uid: jsmith
userPassword: scrambled

dn: cn=developers,ou=groups,dc=parascus,dc=de
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=jsmith,ou=people,dc=parascus,dc=de

现在我在我的控制器方法中并尝试获取 cn 属性“Smith, John”:

@GetMapping("/profile")
public String index(Authentication authentication) {
    return "Profile of " + authentication.getName();
}

但我只得到 uid“jsmith”。有人可以提示我如何获取所有信息或最后的 cn 条目吗?

亲切的问候

帕拉斯库斯

标签: authenticationspring-securityspring-ldap

解决方案


您将需要提供一个UserDetailsContextMapper告诉 Spring Security 如何从DirContext.

你在暴露LdapAuthenticationProvider时这样做:

@Bean
LdapAuthenticationProvider ldap(LdapAuthenticator authenticator) {
    LdapAuthenticationProvider ldap = new LdapAuthenticationProvider(authenticator);
    ldap.setUserDetailsContextMapper(new PersonContextMapper());
    return ldap;
}

Spring Security 附带了几个内置的上下文映射器,一个用于person模式 ( PersonContextMapper),另一个用于inetOrgPerson模式 ( InetOrgPersonContextMapper)。

使用上述配置,您可以执行以下任一操作:

public String index(Authentication authentication) {
    Person person = (Person) authentication.getPrincipal();
    String[] cn = person.getCn();
    return "Profile of " + cn[cn.length - 1];
}

或者

public String index(@AuthenticationPrincipal Person person) {
    String[] cn = person.getCn();
    return "Profile of " + cn[cn.length - 1];
}

如果您的条目既不使用person也不使用inetOrgPerson架构,您可以创建自己的UserDetailsContextMapper.


推荐阅读