I'm authenticating users against an LDAP server and I need to see if the user belongs to a particular group. All users belonging to a subgroup under this group should also be allowed to login. Here's the code I'm currently using:
private String[] returnedAtts = { "sn", "givenName", "mail", "objectSid", "memberOf" };
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(returnedAtts);
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
LdapContext ldatCtxt = null;
try{
ldatCtxt= getInitialContext(userName, password);
}
catch(AuthenticationException e){
throw new AppException(AppMessageHandler.getClientString("invalidCredentials"));
}
String searchFilter = userSearchQuery.replace("$USERID$", userName);
NamingEnumeration<?> answer = ldatCtxt.search(searchBase, searchFilter,searchCtls);
String userGroup=null;
if(answer==null || !answer.hasMoreElements()){
throw new AppLoginException(AppMessageHandler.getClientString("invalidCredentials"));
}
SearchResult searchresult = (SearchResult) answer.next();
Attribute memberOf = (Attribute) searchresult.getAttributes().get("memberOf");
if(memberOf==null){
throw new AppLoginException(AppMessageHandler.getClientString("userNotInADGroup"));
}
userGroup = (String) memberOf.get();
String[] groups=userGroup.split(",");
boolean isMemberOfGroup = false;
for(String groupName:groups)
{
if(groupName.equals("CN="+appUserGrp))
isMemberOfGroup = true;
}
if(!isMemberOfGroup){
throw new AppLoginException(AppMessageHandler.getClientString("userNotInADGroup"));
}
This works fine when I'm checking for a specific group, but doesn't work when a user from a subgroup(which is a member of the parent group - appUserGrp. Is there a way to check if a user belongs to a specific group or any subgroup that is a member of that group?
Here's a sample of the group structure that I have:
Group1
SubGroup1
-User3
-User4
SubGroup2
-User5
Group2
User1-5 should be able to login, but user6 and user7 should not be able to login.
I am assuming as you show searching for "ObjectSid", you are using Microsoft Active Directory. If so, You can to use the extensible matching filter using LDAP_MATCHING_RULE_IN_CHAIN. Query the group with the scope=BASE and Something like:
(member:1.2.840.113556.1.4.1941:=CN=John Smith,DC=MyDomain,DC=NET)
Should work.