Java LDAP - Determine if user in a given group?

后端 未结 10 789
时光取名叫无心
时光取名叫无心 2020-12-12 20:18

We logon users to Active Directory via LDAP using the Java LDAP API. We want to enhance our logon functionality to further check if the user is in a given AD group. Does a

10条回答
  •  执笔经年
    2020-12-12 20:49

    Following up on Sundaramurthi's answer, it could be done even more straightforward way, where you don't query for all the user's group:

    (&(objectClass=user)(sAMAccountName=XXXX)(memberOf=CN=YYY,OU=_Common-Access,OU=Groups,OU=_CORP,DC=XXX,DC=XX))
    

    where XXXX - user name XXX.XX - domain name YYY - group name

    This lets you to just get an answer whether user is in a group or not.

    So just do:

    String userBase = "DC=XXX,DC=XX";
    String CHECK_IF_USER_IN_GROUP = "(&(objectClass=user)(sAMAccountName=%s)(memberOf=CN=%s,OU=...,OU=...,OU=...,%s))";
    
    String queryFilter = String.format(CHECK_IF_USER_IN_GROUP, user, group, userBase);
    
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    
    NamingEnumeration results = context.search(userBase, queryFilter, constraints);
    
    if (results == null) {
        throw new Exception("No answer from LDAP");
    }
    
    if (!results.hasMore()) {
        System.out.println("No result found");
        // user is not in the group
    }
    // user is in the group
    

提交回复
热议问题