title: Java LDAP Authentication using username and password
body: <p>I have a working code snippet by which i can authenticate a user by <code>dn</code> and password. My requirement is that the user will be entering his username(<code>sAMAccountName</code>) and I want to authenticate using <code>sAMAccountName</code> and password. How can I modify this code to achieve it?</p>
  
  <pre><code>    String userName = "John P R-Asst General Manager";
      String passWord = "asdfgh123";
      String base ="OU=SOU,DC=example,DC=com";
      String dn = "cn=" + userName + "," + base;
  
      String ldapURL = "ldap://mdsdc3.example.com:389";
      authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
      authEnv.put(Context.PROVIDER_URL, ldapURL);
      authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
      authEnv.put(Context.SECURITY_PRINCIPAL, dn);
      authEnv.put(Context.SECURITY_CREDENTIALS, password);
  
      try {
          DirContext authContext = new InitialDirContext(authEnv);
          return true;
  
      } catch (NamingException namEx) {
          return false;
      }
  </code></pre>