Springsecurity LDAP authentication sample XML.
uid={0},ou=People
cn
sn
uid
1. Implements UserDetailsContextMapper
public class UserDetailsContextMapperImpl implements UserDetailsContextMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection
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
getGrantedAuthorities(DirContextOperations userData, String username) {
return new ArrayList
() {
private static final long serialVersionUID = 1L;
{
add(new SimpleGrantedAuthority(ROLE_USER));
}
};
}
}
3. UserDN pattern
According to practical how do you manage user information on LDAP server.
For example, uid={0},ou=Users
4. User attributes
Attributes will return to application from LDAP server after success authentication. If you don't specify LDAP server will return all the attributes of this authenticated user.
For example, uid, cn and sn etc.