我正在使用带有LDAP的Spring Security(Active Directory),我可以通过扩展LdapUserDetailsMapper来验证用户并创建我自己的用户详细信息对象。
默认情况下,我获得某些字段和组以及DN
但是我希望获得其他字段,例如电子邮件,联系电话号码,这些字段在Active Directory中可用。
那么如何获取这些信息?
我的配置
@Bean
public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider("hmie.co.in", "ldap://1.1.1.1:389/");
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
provider.setUserDetailsContextMapper(userDetailsContextMapper);
return provider;
}
自定义用户详细信息映射
@Service
public class MyUserDetailsContextMapper extends LdapUserDetailsMapper implements UserDetailsContextMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
LdapUserDetailsImpl ldapUserDetailsImpl = (LdapUserDetailsImpl) super.mapUserFromContext(ctx, username, authorities);
MyUserDetails myUserDetails = new MyUserDetails();
myUserDetails.setAccountNonExpired(ldapUserDetailsImpl.isAccountNonExpired());
myUserDetails.setAccountNonLocked(ldapUserDetailsImpl.isAccountNonLocked());
myUserDetails.setCredentialsNonExpired(ldapUserDetailsImpl.isCredentialsNonExpired());
myUserDetails.setEnabled(ldapUserDetailsImpl.isEnabled());
myUserDetails.setUsername(ldapUserDetailsImpl.getUsername());
myUserDetails.setAuthorities(ldapUserDetailsImpl.getAuthorities());
String dn = ldapUserDetailsImpl.getDn();
int beginIndex = dn.indexOf("cn=") + 3;
int endIndex = dn.indexOf(",");
myUserDetails.setEmployeeName(dn.substring(beginIndex, endIndex));
beginIndex = dn.indexOf("ou=") + 3;
endIndex = dn.indexOf(",", beginIndex);
myUserDetails.setDepartment(dn.substring(beginIndex, endIndex));
return myUserDetails;
}
}
答案 0 :(得分:0)
要获取完整的LDAP目录属性和值,我确实喜欢这样。但在这里,我使用的是inteface org.springframework.ldap.core.AttributesMapper
而不是类org.springframework.security.ldap.userdetails.LdapUserDetailsMapper
。
ldapTemplate.search("o=XXXXX", new EqualsFilter("uid", userName).encode(),
new AttributesMapper() {
@Override
public Object mapFromAttributes(Attributes attr) throws NamingException {
// TODO Auto-generated method stub
NamingEnumeration<String> namingEnumeration = attr.getIDs();
while (namingEnumeration.hasMoreElements()) {
String attributeName= (String) namingEnumeration.nextElement();
System.out.println(attributeName+" = "+attr.get(attributeName));
}
return null;
}
});
在上面的代码中attr.getIDs()
返回Active目录属性,如CN,DN,SN和邮件。 attr.get(attribute)
返回属性值。
答案 1 :(得分:0)
mapUserFromContext
中的代码是所以关闭!关键细节是传入方法的ctx
对象已包含主体的其他Active Directory属性。可以使用方法ctx.getStringAttribute("attribute-name")
访问属性值。例如,您将使用ctx.getStringAttribute("sn")
访问主体的姓氏属性。要获取用户的电子邮件和联系号码,您只需要访问相应的属性。在我公司的Active Directory中,这些属性分别是 mail 和 phone 。您的系统中的属性名称可能会有所不同。