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?
There is no entry whose DN contains a UID or CN=username. You have to provide an entry which exists, not just an arbitrary string of attributes. The usual technique is to bind as an admin user, search for the user who has that UID or whatever he provided to your login system, retrieve the DN of that user, then try to bind as that DN with the user-supplied oassword.
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:
This way I don't care about the DN. Just passing the username@domain and voila - works like a charm :) Thanks again!