title: Query active directory Using Java for samaccountname's Tied to a Specific Group
body: <p>Hi the below LDAP query returns a list of members' "givenName", that are in a specific group. However, I would to return a list of members' "sAMAccountName", that are in a specific group. I'm not very familiar with LDAP and unsure how to accomplish this. Any help is appreciated.</p>
  
  <pre><code>    public LdapContext getLdapContext(){
          LdapContext ctx = null;
          String connection = null;
          try{
              Hashtable&lt;String, String&gt; env = new Hashtable&lt;String, String&gt;();
              env.put(Context.INITIAL_CONTEXT_FACTORY,
                      "com.sun.jndi.ldap.LdapCtxFactory");
              env.put(Context.SECURITY_AUTHENTICATION, "Simple");
              env.put(Context.SECURITY_PRINCIPAL, "userPrincipalName");
              env.put(Context.SECURITY_CREDENTIALS, "Password");
              env.put(Context.PROVIDER_URL, "domainController");
              ctx = new InitialLdapContext(env, null);
              connection = "Connection Successful.";
          }catch(NamingException nex){
              connection = "LDAP Connection: FAILED";
              nex.printStackTrace();
          }
          this.getUserBasicAttributes("(&amp;(objectClass=group)(CN=Users_Group))", ctx);
          return ctx;
      }
  
      private void getUserBasicAttributes(String groupID, LdapContext ctx) {
          try {
              String userName = null;
              String member = null;
  
              SearchControls constraints = new SearchControls();
              constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
              String[] attrIDs = {"member"};
              constraints.setReturningAttributes(attrIDs);
              NamingEnumeration answer = ctx.search("DC=Domain,DC=com", groupID, constraints);
              if (answer.hasMore()) {
                  Attributes attrs = ((SearchResult) answer.next()).getAttributes();
                  member = attrs.get("member").toString();
              }else{
                  throw new Exception("Invalid Group");
              }
          } catch (Exception ex) {
              ex.printStackTrace();
          }
          return;
      } 
  </code></pre>
  
  <p>Results of the above query look similar to below:</p>
  
  <pre><code>member: CN=FistName 
  LastName,OU=ouData,OU=ouData,OU=ouData,DC=dcData,DC=dcData,DC=dcData, 
  CN=FistName2 
  LastName2,OU=ouData,OU=ouData,OU=ouData,DC=dcData,DC=dcData,DC=dcData, 
  CN=FistName3 
  LastName3,OU=ouData,OU=ouData,OU=ouData,DC=dcData,DC=dcData,DC=dcData, 
  CN=FistName4 
  LastName4,OU=ouData,OU=ouData,OU=ouData,DC=dcData,DC=dcData,DC=dcData
  </code></pre>