apache目录服务器身份验证....告诉我哪里出错了.....我使用的代码.........如下所示

时间:2012-03-06 07:03:25

标签: ldap apacheds

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();
        }
    }
}

上述程序将对用户进行身份验证,并为用户显示dn。在这里我在eclipse中使用Apache ds。从上面的程序我试图得到dn:对于user1谁的基础是ou=users,ou=system但我没有得到dn:for user1。

1 个答案:

答案 0 :(得分:1)

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