使用用户名和密码的Java LDAP身份验证

And*_*eda 19 authentication jndi ldap

我有一个工作代码片段,我可以通过它来验证用户dn和密码.我的要求是用户将输入他的用户名(sAMAccountName),我想使用sAMAccountName和密码进行身份验证.如何修改此代码才能实现?

    String userName = "John P R-Asst General Manager";
    String passWord = "asdfgh123";
    String base ="OU=SOU,DC=example,DC=com";
    String dn = "cn=" + userName + "," + base;

    String ldapURL = "ldap://mdsdc3.example.com:389";
    authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    authEnv.put(Context.PROVIDER_URL, ldapURL);
    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    authEnv.put(Context.SECURITY_PRINCIPAL, dn);
    authEnv.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext authContext = new InitialDirContext(authEnv);
        return true;

    } catch (NamingException namEx) {
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

小智 45

我希望这可以帮助你们中的许多人.

您不需要具有CN,DN等的所有用户层次结构.

您只需登录通过域\用户和密码即可登录.

我的代码工作原理如下:

try
    {
        // Set up the environment for creating the initial context
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://ldap_server:389");
        // 
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "domain\\user"); //we have 2 \\ because it's a escape char
        env.put(Context.SECURITY_CREDENTIALS, "test");

        // Create the initial context

        DirContext ctx = new InitialDirContext(env);
        boolean result = ctx != null;

        if(ctx != null)
            ctx.close();

        return result;
    }
    catch (Exception e)
    {           
        return false;
    }
Run Code Online (Sandbox Code Playgroud)


JPB*_*anc 2

你可以尝试Context.PROVIDER_URL这样完成:

String ldapURL = "ldap://mdsdc3.example.com:389/DC=example,DC=com";
Run Code Online (Sandbox Code Playgroud)

我认为使用 GSSAPI 会更好,也许你可以看看这里这里