LDAP Code to connect LDAP Server using Java and Retrieve User Groups
public List<String> getUserGroupsfromLDAP(HttpServletRequest request, String userName) throws GeneralSecurityException {
LOG.info("Using LDAP to lookup User Groups. Current connection string - " + LDAP_IP);
//Create the env variable to user for the connection to the LDAP server
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, LDAP_IP);
LOG.info("Current Authentication string - User " + LDAP_USER + " and Password " + LDAP_PASSWORD);
//Add the Authentication to the env variable.
if (StringUtils.isNotBlank(LDAP_USER)) {
env.put(Context.SECURITY_AUTHENTICATION, LDAP_AUTHENTICATION_TYPE);
env.put(Context.SECURITY_PRINCIPAL, LDAP_USER);
env.put(Context.SECURITY_CREDENTIALS, LDAP_PASSWORD);
} else {
LOG.info("No LDAP user property specified. Authenticator will attempt to connect to LDAP anonymously.");
}
LOG.info("LDAP properties: " + env);
// Let's try an initial connection and context and fail if we don't get it.
LOG.info("Connecting to LDAP server...");
// Create initial context
DirContext ctx;
try {
ctx = new InitialDirContext(env);
LOG.info("Connection to LDAP server SUCCEEDED.");
} catch (NamingException e) {
throw new GeneralSecurityException("Unable to connect to primary LDAP server. Connection Failed!",e);
}
List<String> groupList = new ArrayList<String>();
try {
//Set Search Controls scope to the SubTree and set the Limit to unlimited
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setCountLimit(0);
String ldapFilter = StringUtils.isNotBlank(LDAP_USER_GROUP_FILTER) ? String.format(LDAP_USER_GROUP_FILTER, userName) : userName;
LOG.info(String.format("Searching [%s] with filter %s", LDAP_USER_GROUP_QUERY, ldapFilter));
//Search for objects that have those matching attributes
NamingEnumeration<SearchResult> answer = ctx.search(LDAP_USER_GROUP_QUERY, ldapFilter, sc);
if (answer.hasMoreElements()) {
LOG.info("The search query returned results to process.");
NamingEnumeration<?> answerAttributes;
StringTokenizer st;
/* For each record in the query + filter get all requested attributes via the
* ATTRIBUTE variable. For each attribute, use the string tokenizer to break the
* string into sections and check for a sub attribute equal to the PRINCIPAL variable.
* When it is found get the next value in the string tokenizer and add it to the group list.
*/
if(answer.hasMore()){
LOG.info("Inside Answer Attributes");
answerAttributes = answer.next().getAttributes().get(LDAP_RESULT_ATTRIB).getAll();
while(answerAttributes.hasMore()){
LOG.info("Inside Answer Attributes has More" );
st = new StringTokenizer(answerAttributes.next().toString(),USER_GROUPS_DELIMITER);//+,=
while(st.hasMoreTokens()){
if(LDAP_RESULT_PRINCIPAL.equals(st.nextToken()) && st.hasMoreTokens()){
groupList.add(st.nextToken());
LOG.info("Group Attributes found ::: " + Arrays.toString(groupList.toArray()));
}
}
}
}
} else {
LOG.info("The search query returned no results. End SSO Authentication.");
}
LOG.info("Completed the retrieval of the Groups associated with the current User. There are " + groupList.size() + " Groups." );
} catch (NamingException e) {
LOG.fatal("There was a Naming Exception error while retrieving the attributes from the LDAP server.");
throw new GeneralSecurityException("Unable to complete SSO authentication due to Naming Exception from LDAP server.", e);
}
try{
ctx.close();
}
catch (NamingException e) {
LOG.fatal("There was a Naming Exception error while closing the connection to the LDAP server.");
throw new GeneralSecurityException("There was a Naming Exception error while closing the connection to the LDAP server.", e);
}
return groupList;
}
Comments
Post a Comment