At Microsoft Professional Developer Conference (PDC) 2005, in the Sun booth we talked about interoperability between .NET and Java. One of the demo we showed is about authenticating a JSF web application (created using Sun Java Studio Creator) using Microsoft Active Directory Service running in a Windows 2003 box. Several participants showed interest and wanted to know the detail behind it.
Logically it is very simple. MS Active Directory Service (ADS) supports LDAP (Lightweight Directory Access Protocol) at the port 389. One of the protocol supported by Java Naming and Directory Interface (JNDI), which is part of the Java platform, is LDAP. So from the Java Studio Creator generated web application we connect to ADS using JNDI implementation of LDAP at port 389.
Following sample code (written by one of our interns, Saniya) can be add to a JSF page in the web application to do the authentication
private String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
// Windows 2003 server running Active Directory Service
private String MY_HOST = "ldap://mydomain.myhost:389";
String username = (String)usernameTxtField.getValue();
String password = (String)passwordTxtField.getValue();
DirContext ctx = null;
try{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,INITCTX);
env.put(Context.PROVIDER_URL, MY_HOST);
env.put(Context.SECURITY_PRINCIPAL,"CN="+username+",CN=Users,DC=rave,DC=com");
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.SECURITY_AUTHENTICATION,"simple");
ctx = new InitialDirContext(env);
}catch(javax.naming.AuthenticationException authex){
error("Authentication Exception: Please Check Your Username and Password");
// Your logic here to handle Authentication Error
}catch(Exception exc){
error(exc.getLocalizedMessage());
// Your logic here to handle other errors
}
// No error, user authenticated
Above sample code is a very simple method. There are possibilities to use more sophisticated methods, which I'll try to cover in another blog.
BTW, currently in Java Studio Creator, users need to manually add code to the java source to connect to any LDAP supported authentication service. I would like to see a simple JSF (non visual) component with proper customization in the Creator toolbox, which when added to the page should do the authentication transparently for the user, when the username and password is supplied to it - may be in the future release.