0
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class AdvancedBindDemo2 {

    public static void main(String[] args) throws NamingException {

        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        String uid = "user1";//supplying userid manually
        String password = "secret";

        DirContext ctx = null;
        try {            
            // Step 1: Bind anonymously            
            ctx = new InitialDirContext(env);

            // Step 2: Search the directory
            String base = "ou=users,ou=system";//base
            String filter = "(objectClass=*)";           
            SearchControls ctls = new SearchControls();
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            ctls.setReturningAttributes(new String[0]);
            ctls.setReturningObjFlag(true);
            NamingEnumeration enm = ctx.search(base, filter, new String[] { uid }, ctls);

            String dn = null;
            if (enm.hasMore()) {
                SearchResult result = (SearchResult) enm.next();
                dn = result.getNameInNamespace();

                System.out.println("dn: "+dn);
            }

            if (dn == null || enm.hasMore()) {
                // uid not found or not unique
                throw new NamingException("Authentication failed");
            }

            // Step 3: Bind with found DN and given password
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            // Perform a lookup in order to force a bind operation with JNDI
            ctx.lookup(dn);
            System.out.println("Authentication successful");

        } catch (NamingException e) {
            System.out.println(e.getMessage());
        } finally {
            ctx.close();
        }
    }
}

The above program will authenticate a user as well as it will show the dn for the user. And here I am using Apache ds in eclipse. From the above program I am trying to get the dn: for user1 who's base is ou=users,ou=system but I am not getting the dn: for user1.

4

1 回答 1

1

假设 user1 的 DN 是“uid=user1,ou=users,ou=system”,那么您的过滤器应该更改为“(uid=user1)”。另请注意,您请求的属性应该是错误的 - new String[] { "uid" }

于 2012-03-07T16:36:35.010 回答