Thursday, November 16, 2006

GlassFish + JNDI + LDAP + JAVA

STEP 1: Create JNDI LDAP Resource

In the GlassFish admin console create a JNDI Custom Resource with the following parameters:

1. Give it a JNDI name such as myLDAP
2. Resource Type: javax.naming.directory.Directory
3. Factory Class: com.sun.jndi.ldap.LdapCtxFactory

Add the following as additional parameters:

1. Name: java.naming.security.principal Value: the reader dn

2. Name:java.naming.security.credentials Value: the password

3. Name: URL Value: ldap://servername/baseDN

STEP 2: JAVA code to access the LDAP

Use code similar to the following to access the LDAP:

try {
Context initCtx = new InitialContext();
DirContext ctx = (DirContext) initCtx.lookup("myLDAP");

SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

String searchfilter = "(mail="+ email +")";
NamingEnumeration answer = ctx.search("", searchfilter, ctls);

if(answer.hasMore()){
SearchResult entry = (SearchResult) answer.next();
Attributes attrs = entry.getAttributes();
......

} else {
success = false;
}
} catch (NamingException e) {
e.printStackTrace();
}

2 comments:

Nachiket Patel said...

Thanks, Sud.
I want ask one question.
If i want to use Windows Active Directory User-Password for Login in client application (of Glassfish server application), How to use it?

I think, Windows AD <=> LDAP <=> JNDI <=> My app. But what will be the look up key?

Will you be able to give other information??


This is my email : patel.nachiket.r@gmail.com

Regards,
Nachiket

Allan Lykke Christensen said...

Seems like com.sun.jndi.ldap.LdapCtxFactory is not picking up the authentication properties java.naming.security.principal and java.naming.security.credentials. I keep getting javax.naming.NoPermissionException. Any idea what properties to use to force LdapCtxFactory to authenticate?