Java LDAP - Determine if user in a given group?

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

    Also you can modify the accepted answer from here: Authenticating against Active Directory with Java on Linux with the following:

    String group="name of the group";
    Iterator ig = groups.iterator();
    Boolean bool=false;
    while (ig.hasNext()) {
          String a=ig.next().toString();
          if (a.equals(group)) { 
                    JOptionPane.showMessageDialog(this, "Authentication succeeded!");   
                    bool=true;
                    // here you can do smth in case of success  
          }
    }
    if (bool==false){
                 JOptionPane.showMessageDialog(this, "Permission denied");   
    }
    
    0 讨论(0)
  • 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;
     }
    
    0 讨论(0)
  • 2020-12-12 21:07

    I can't give you a working code using java naming ldap. I used Spring LDAP, and the way you do it: Get the User object, do a search on the username something like sAMAccountName=USERNAME

    After you get the object you retreive the property memberOf -> this will be a list and check for a specific one in Java.

    That is the only way I could think of.

    0 讨论(0)
  • 2020-12-12 21:07

    Unfortunately the answer varies with installations of AD as well as other types of LDAP server.

    We had to solve the same problem. In the end we allowed the system administrator to provide us with an LDAP query-pattern where we substitute the user name (and group name if that needs to be variable too) into the pattern.

    0 讨论(0)
提交回复
热议问题