title: java - Active Directory - authentication using base dn
body: <p>I have writeen a test code for authenticating user through Active Directory server. I am able to authenticate using bind dn using code below.</p>
  
  <pre><code>public static void main(String[] args) {
  
      LdapContext ldapContext = null;
  
      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.PROVIDER_URL, "ldaps://10.121.85.24:636");
      env.put(Context.SECURITY_PROTOCOL, "ssl");
      env.put(Context.SECURITY_PRINCIPAL, "EXTLDAPTEST\batty"); // line 1
      env.put(Context.SECURITY_CREDENTIALS, "mypassword");
      env.put("com.sun.jndi.ldap.read.timeout", Integer.toString(8000));
      env.put("java.naming.ldap.factory.socket", "com.auth.server.TrustAllSSLSocketFactory" );
  
      try {
          ldapContext = new InitialLdapContext(env, null);
      } catch (Exception e) {
          e.printStackTrace();
      }
  
      if (ldapContext != null)
      {
          System.out.println("Authenticatied");
      }
  }
  </code></pre>
  
  <p>But when I replace line 1 with </p>
  
  <pre><code>env.put(Context.SECURITY_PRINCIPAL, "CN=batty,OU=Unsorted,OU=EDN Users,OU=User accounts,DC=extLDAPTest,DC=local"); // line 1
  </code></pre>
  
  <p>it throws exception as</p>
  
  <blockquote>
    <p>javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1</p>
  </blockquote>
  
  <p>AD's tree structure is :</p>
  
  <p><a href="https://i.stack.imgur.com/E1zAw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E1zAw.jpg" alt="enter image description here"></a></p>
  
  <p>Am I doing something wrong when trying to use full dn for authentication?</p>
  
  <p><strong>EDIT 1</strong>:
  When I use service account to get full dn using </p>
  
  <pre><code>NamingEnumeration&lt;?&gt; aa = context.list("OU=Unsorted,OU=EDN Users,OU=User accounts,DC=extLDAPTest,DC=local");
  </code></pre>
  
  <p>I get following result:</p>
  
  <blockquote>
    <p>CN=batty,OU=Unsorted,OU=EDN Users,OU=User accounts,DC=extLDAPTest,DC=local</p>
  </blockquote>
  
  <p>Which is same as I passed for authentication. </p>
  
  <p><strong>EDIT 2</strong> : the reason I am using full dn is, I will be given service account and dn of an sub-tree. Now, same user can exists in different subtrees. So I want to authenticate it from a specific sub tree.</p>