繁体   English   中英

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

[英]LDAP user password authentication using JNDI

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

我想问一下,当我将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]

当我被指定为cn=John而不是uid=103时,我被认证了。 我不允许用uid指定吗?

如果您事先不知道确切的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 ...

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

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

它看起来像服务器配置问题。 这是一个类似的问题,包括一个解决方案 基本上,您必须在ldap-authentication.properties指定是否使用uidcn进行身份验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM