Java, LDAP and Active Directory
Posted 2005 Feb 24Interface a Java application with Active Directory is a common albeit convulted endeavor. After struggling with unhelpful error codes for too long, I’ve decided to post some information that I found invaluable. First, there are a series of posts on the Sun forums that cover most of the topics:
- Changing Passwords
- AD Error Codes and the official MSDN error code reference
- Checking Group Membership
<pre><code> env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapURL ); env.put(Context.SECURITY_PRINCIPAL, adminUser); env.put(Context.SECURITY_CREDENTIALS, adminPassword); env.put("java.naming.ldap.version","3"); env.put(Context.REFERRAL, "follow"); try { LdapContext ctx = new InitialLdapContext(env,null); String USER_TO_CHANGE = "CN=" + userName + ",OU=[your org. unit],DC=[your domain],DC=com"; String NEW_PASSWORD = userPass; ModificationItem[] mods = new ModificationItem [ 1 ] ; mods [ 0 ] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userpassword", NEW_PASSWORD)); ctx.modifyAttributes(USER_TO_CHANGE, mods); ctx.close(); // ... </code>In this code the admin account logs in and sets a user’s password. I was unable to get a user to change his or her own password, even though AD was configured to do so… Check the links above for details on how to do that.
It is also worth noting that contrary to many posts SSL is not required to perform these operations.
With regards to Error Messages, there is an art to decoding those… An exception will usually include a message like so:
The part we’re after is the “data 775”. That is the hexadecimal error code. So, simply convert it to decimal, then consult the error code list. In this case, the error code is decimal 1909: ERROR_ACCOUNT_LOCKED_OUT. I built a simple lookup table of common error messages, then parse the error message like so:[LDAP: error code 49 – 80090308: LdapErr: DSID-0C09030F, comment: AcceptSecurityContext error, data 775, vece]
<pre><code> String err = e.getMessage(); // where e is the exception int i = err.indexOf("data ")+5; int j = err.indexOf(",",i); System.out.println(err.substring(i,j)); </code>
Like I said, interfacing Java, LDAP and Active Directory to authorize, change passwords, and check group membership tricky—but possible. I hope this guide will help get you started.
GT
2005 Dec 06 at 00:54Thanks very much, stumbled across this from google with the exact problem and thanks to this found a quick resolution as to what was causing our problem.