使用JNDI进行LDAP用户密码身份验证

Niv*_*vek 9 java jndi ldap

public static void main(String[] args)
{
    String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = "ldap://Localhost:1389";
    String MGR_DN = "cn=John,ou=Users,o=IT,dc=QuizPortal";
    String MGR_PW = "password";           

    //Identify service provider to use
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, INITCTX);
    env.put(Context.PROVIDER_URL, MY_HOST);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, MGR_DN);
    env.put(Context.SECURITY_CREDENTIALS, MGR_PW);

    try
    {
        // Create the initial directory context
        InitialDirContext initialContext = new InitialDirContext(env);

        System.out.println("Context Sucessfully Initialized");
    }
    catch(Exception e)
    {
        System.err.println(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想问我什么时候MGR_DN = "cn=John,ou=Users,o=IT,dc=QuizPortal"开始MGR_DN = "uid=103,ou=Users,o=IT,dc=QuizPortal".基本上从cn变为uid,我会遇到错误

javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
Run Code Online (Sandbox Code Playgroud)

我被指定为cn=John但未经过身份验证uid=103.我不允许用uid指定吗?

Bru*_*uno 8

如果您事先不知道确切的DN,则应首先在LDAP目录中进行搜索.这可以或多或少地像这样做(确保你捕获相关的例外):

Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapServerUrl);
env.put(Context.SECURITY_AUTHENTICATION, "none");

SearchControls searchCtrls = new SearchControls();
searchCtrls.setReturningAttributes(new String[] {});
searchCtrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

String filter = "(&(cn=" + identifier + "))";

DirContext ctx = null;
ctx = new InitialDirContext(env);
NamingEnumeration<SearchResult> answer = ctx.search(
   ldapBaseDN, filter, searchCtrls);

String fullDN = null;
if (answer.hasMore()) {
    fullDN = answer.next().getNameInNamespace();

    ctx.close();
    ctx = null;

    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fullDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    ctx = new InitialDirContext(env);
    return true;
}
// Exception otherwise ...
Run Code Online (Sandbox Code Playgroud)

这里,搜索过滤器是"(&(cn=" + identifier + "))"(例如(&(cn=John))),但您可以使用uid替代.结果的唯一性取决于LDAP服务器的配置.基本DN还取决于它的设置方式(可能ou=Users,o=IT,dc=QuizPortal在您的示例中).


use*_*421 4

您必须指定 DN 或专有名称。这是用户在目录中绑定的名称。您不能只选择任何属性链。如果您的用户通过“cn”属性绑定,则只有“cn”属性是 DN 的一部分。