问题描述
我正在使用 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=de
objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=jsmith,ou=people,dc=de
objectclass: top
objectclass: person
objectclass: inetorgPerson
cn: Smith,John
sn: Smith
uid: jsmith
userPassword: scrambled
dn: cn=developers,ou=groups,dc=de
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=jsmith,dc=de
现在我在我的控制器方法中并尝试获取 cn 属性“Smith,John”:
@GetMapping("/profile")
public String index(Authentication authentication) {
return "Profile of " + authentication.getName();
}
但我只得到 uid "jsmith"。有人可以提示我如何获取所有信息或最终获取 cn 条目吗?
亲切的问候
Parascus
解决方法
您需要 supply a UserDetailsContextMapper
告诉 Spring Security 如何从 DirContext
中提取详细信息。
您在 exposing the 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
。