Alex Rivera | Logout

Java LDAP - Determine if user in a given group?

Asked 2009-02-20T17:18:06.973
31

We logon users to Active Directory via LDAP using the Java LDAP API. We want to enhance our logon functionality to further check if the user is in a given AD group. Does anyone know how to do this?

Current code:

import javax.naming.*;
import javax.naming.ldap.*;

LdapContext ctx = null;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.PROVIDER_URL, Config.get("ldap-url"));

try {
    Control[] connCtls = new Control[] {new FastBindConnectionControl()};
    ctx = new InitialLdapContext(env, connCtls);
    ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, "DOMAIN\\" + username);
    ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
    ctx.reconnect(connCtls);
    /* TODO: Only return true if user is in group "ABC" */
    return true; //User authenticated
} catch (Exception e) {
    return false; //User could NOT be authenticated
} finally {
    ...
}

Update: See the solution below.

Edit
Report

1 Answer

1

I can't give you a working code using java naming ldap. I used Spring LDAP, and the way you do it: Get the User object, do a search on the username something like sAMAccountName=USERNAME

After you get the object you retreive the property memberOf -> this will be a list and check for a specific one in Java.

That is the only way I could think of.

answered 2009-02-20T17:27:53.813

Your Answer