Java 使用用户名进行 LDAP 身份验证

Java LDAP authentication with username

好吧,这让我发疯。我正在尝试使用 Java 创建 LDAP 身份验证,如果我在 SECURITY_PRINCIPAL 中使用我的名字和姓氏,一切都很好。这是我的代码:

 try {
    Hashtable<String, String> ldapEnv = new Hashtable<String, String>();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL,  "LDAP://myldap.mydomain.com:389");
    ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    ldapEnv.put(Context.SECURITY_PRINCIPAL, "CN=FirstName LastName" + ",ou=Users");    
    ldapEnv.put(Context.SECURITY_CREDENTIALS, "password");

    DirContext ldapContext = new InitialLdapContext(ldapEnv, null);
    }
    catch (Exception e) {
      System.out.println(" bind error: " + e);
      e.printStackTrace();
   }

问题是它不适用于我的用户名。如果我尝试:

ldapEnv.put(Context.SECURITY_PRINCIPAL, "CN=myusername" + ",ou=Users");

ldapEnv.put(Context.SECURITY_PRINCIPAL, "uid=myusername" + ",ou=Users");

我总是得到 [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1]

出于某种原因,这似乎只适用于我的名字和姓氏。我检查了广告,我的 sAMAccountName 是我正确的用户名。不知道为什么会这样。其他人有这样的问题吗?我可以将其他内容传递给 Context.SECURITY_PRINCIPAL 吗?我尝试了 ldapEnv.put(Context.SECURITY_PRINCIPAL, "sAMAccountName=myusername" + ",ou=Users"); 但它也失败了...有人可以帮忙吗?

没有条目的 DN 包含 UID 或 CN=用户名。您必须提供一个存在的条目,而不仅仅是任意的属性字符串。通常的技术是绑定为管理员用户,搜索具有该 UID 的用户或他提供给您的登录系统的任何内容,检索该用户的 DN,然后尝试使用用户提供的 oassword 绑定为该 DN。

EJP,感谢您的意见。你确实是正确的,但我正在寻找一些简单的东西——只需将用户名和密码传递给 AD,看看它是否通过身份验证。我应该在我的第一个 post 中更具体。你的建议会奏效,但我认为这要简单得多:

            Hashtable props = new Hashtable();
            String principalName = "username@mydomain.com";
            props.put(Context.SECURITY_PRINCIPAL, principalName);
            props.put(Context.SECURITY_CREDENTIALS, "mypassword");
            DirContext context;

                //try to authenticate
            try {

                   context = com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance("LDAP://myldap.mydomain.com:389" + '/', props);
                   context.close();                    
            }

这样我就不关心DN了。只需传递 username@domain 和瞧 - 就像一个魅力 :) 再次感谢!