Search code examples
javaldap

Java LDAP authentication with username


Ok, this is driving me crazy. I'm trying to create an LDAP authentication with Java and everything is fine if I use my First name and Last name in the SECURITY_PRINCIPAL. This is my code:

 try {
    Hashtable<String, String> ldapEnv = new Hashtable<String, String>();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL,  "LDAP://myldap.mydomain.com:389");
    ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    ldapEnv.put(Context.SECURITY_PRINCIPAL, "CN=FirstName LastName" + ",ou=Users");    
    ldapEnv.put(Context.SECURITY_CREDENTIALS, "password");

    DirContext ldapContext = new InitialLdapContext(ldapEnv, null);
    }
    catch (Exception e) {
      System.out.println(" bind error: " + e);
      e.printStackTrace();
   }

The problem is that it does not work with my username. If I try:

ldapEnv.put(Context.SECURITY_PRINCIPAL, "CN=myusername" + ",ou=Users");

Or

ldapEnv.put(Context.SECURITY_PRINCIPAL, "uid=myusername" + ",ou=Users");

I always get [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1]

This only seems to work with my First name and Last name for some reason. I checked the AD and my sAMAccountName is my correct username. Not sure why this is happening. Anyone else had such issues? Can I pass something else to Context.SECURITY_PRINCIPAL? I tried ldapEnv.put(Context.SECURITY_PRINCIPAL, "sAMAccountName=myusername" + ",ou=Users"); but it also fails... Can anyone please help?


Solution

  • EJP, thanks for your input. You are indeed correct but I was looking for something simple - just pass a username and password to the AD and see if it authenticates or not .I should have been more specific in my first post. Your suggestion will work but I think this is much simpler:

                Hashtable props = new Hashtable();
                String principalName = "username@mydomain.com";
                props.put(Context.SECURITY_PRINCIPAL, principalName);
                props.put(Context.SECURITY_CREDENTIALS, "mypassword");
                DirContext context;
    
                    //try to authenticate
                try {
    
                       context = com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance("LDAP://myldap.mydomain.com:389" + '/', props);
                       context.close();                    
                }
    

    This way I don't care about the DN. Just passing the username@domain and voila - works like a charm :) Thanks again!