Springsecurity LDAP authentication sample XML.
uid={0},ou=Peoplecnsnuid
1. Implements UserDetailsContextMapper
public class UserDetailsContextMapperImpl implements UserDetailsContextMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
//How to get attribute from DirContextOperations
try {
System.out.println("Get DN size: " + ctx.getDn().size());
for(int i=0; i< ctx.getDn().size(); i++){
System.out.println("DN[" + i + "] = " + ctx.getDn().get(i));
}
System.out.println("NameInNamespace = " + ctx.getNameInNamespace());
Attributes attributes = ctx.getAttributes();
NamingEnumeration ne = attributes.getIDs();
while(ne.hasMore()){
String id = ne.next();
//System.out.println("id = " + id + ", value = " + ctx.getStringAttribute(id));
//ctx.getStringAttribute(id) is not safe, if attribute is not String object it will throw exception.
Attribute attribute = attributes.get(id);
System.out.println("attribute id:" + id + ", attribute size: " + attribute.size());
for(int j = 0; j < attribute.size(); j++){
System.out.println(" attribute[" + j + "] = " + attribute.get(j));
}
}
} catch (NamingException e) {
e.printStackTrace();
}
//Decide where you want to get user detail information. DB or anywhere you want
UserDetails ud = ...;
return ud;
}
}
2. Implements LdapAuthoritiesPopulator
/**
* Only return "ROLE_USER"
*/
public class LdapAuthoritiesPopulatorImpl implements LdapAuthoritiesPopulator {
public static final String ROLE_USER = "ROLE_USER";
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
return new ArrayList() {
private static final long serialVersionUID = 1L;
{
add(new SimpleGrantedAuthority(ROLE_USER));
}
};
}
}