Authenticating Users with Windows Active Directory from Java


Authenticating Users with Windows Active Directory from Java

Here is a sample code that works with me:

/////////////////////////////////////////////////////////////////////


import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class Main {

public static void main(String[] args) {

try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,
"LDAP://my.ldap.server:389"); //replace with your server URL/IP
//only DIGEST-MD5 works with our Windows Active Directory
env.put(Context.SECURITY_AUTHENTICATION,
"DIGEST-MD5"); //No other SALS worked with me
env.put(Context.SECURITY_PRINCIPAL,
"user1"); // specify the username ONLY to let Microsoft Happy
env.put(Context.SECURITY_CREDENTIALS, "secret1"); //the password

DirContext ctx = new InitialDirContext(env);

ctx.close();

} catch(NamingException ne) {
System.out.println("Error authenticating user:");
System.out.println(ne.getMessage());
return;
}

//if no exception, the user is already authenticated.
System.out.println("OK, successfully authenticating user");
}

////////////////////////////////////////////////////////////////////

I stripped comments to make the blog shorter.

Resources Helped Me:

Notes:

  1. The RFC2829 – http://www.ietf.org/rfc/rfc2829.txt – at section “6. Password-based authentication” states that supporting authentication with a password using the DIGEST-MD5 SASL mechanism is mandatory, so I am confident Microsoft will not drop its support.
  2. This is tested on JDK 1.5, I am sure it works on JRE1.5 and even may work with 1.4.

From ahm507.blogspot.com
,