Love it or hate it so many
organization use LDAP sometimes you just can’t escape it .
For one of my clients I had to migrate the roles from a LDAP to
Database .
As an intermediate step I wrote a method to buid a username ,
groupName map
The usernames were under the attribute uid, the groups were under
the attribute groups
Code Exaple :
private static Map<String,List<String>> userNameRolesMap = new HashMap<String,List<String>>();
private static void populateUsernameRoleMap() throws NamingException{
Hashtable env = new Hashtable();
String PROVIDER_URL = "";
String SECURITY_PRINCIPAL = "";
String SECURITY_CREDENTIALS = "";
if(Constants.RUN_MODE == RunMode.DEV) {
PROVIDER_URL = "ldap://" + Constants.DEV_HOST + ":" + Constants.DEV_PORT + "/" + Constants.DEV_BASEDN;
SECURITY_PRINCIPAL = Constants.DEV_USER;
SECURITY_CREDENTIALS = Constants.DEV_PASSWORD;
}
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, PROVIDER_URL);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, SECURITY_PRINCIPAL );
env.put(Context.SECURITY_CREDENTIALS, SECURITY_CREDENTIALS);
DirContext ctx = null;
NamingEnumeration results = null;
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(10000);
try {
ctx = new InitialDirContext(env);
results = ctx.search("", "(objectclass=auspostUser)", controls);
while (results.hasMore()) {
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
Attribute userNameAttr = attributes.get("uid");
String username = (String) userNameAttr.get();
Attribute groupsAttr = attributes.get("groups");
int numberOfRoles = groupsAttr.size();
List<String> groups = new LinkedList<String>();
for(int i=0;i<numberOfRoles;i++){
String ldapGroupLongName = (String) groupsAttr.get(i);
String databaseGroupName = translateLDAPGroupNameToDbGroupName(ldapGroupLongName);
groups.add(databaseGroupName);
}
userNameRolesMap.put(username,groups);
}
} catch (NamingException e) {
e.printStackTrace();
throw e;
}
}