Java LDAP - Determine if user in a given group?

后端 未结 10 816
时光取名叫无心
时光取名叫无心 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 21:04

    The easiest way is with 'lookup': (to open an Ldap Context: look above examples)

     /**
      * Tests if an Active Directory user exists in an Active Directory group. 
      * @param ctx LDAP Context.
      * @param dnADGroup distinguishedName of group.
      * @param dnADUser distinguishedName of user.
      * @return True if user is member of group.
      */
    
    
    public static boolean isMemberOfADGroup(LdapContext ctx, String dnADGroup, String dnADUser) {
      try {
       DirContext lookedContext = (DirContext) (ctx.lookup(dnADGroup));
       Attribute attrs = lookedContext.getAttributes("").get("member");
       for (int i = 0; i < attrs.size(); i++) {
        String foundMember = (String) attrs.get(i);
        if(foundMember.equals(dnADUser)) {
         return true;
        }
       }
      } catch (NamingException ex) {
       String msg = "There has been an error trying to determin a group membership for AD user with distinguishedName: "+dnADUser;
       System.out.println(msg);
       ex.printStackTrace();
      }
      return false;
     }
    

提交回复
热议问题