Take the 2-minute tour ×

I have a working code snippet by which i can authenticate a user by dn and password. My requirement is that the user will be entering his username(samaccountname) and i want to authenticate using samaccountname and password. How can i modify this code to acheive it??

        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.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;
share|improve this question

2 Answers 2

I hope this helps many of you.

You don't need to all user hierarchy with CN, DN, etc.

You can login just passing domain\user and password.

I've my code working as it is bellow:

        // Set up the environment for creating the initial context
        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)

        return result;
    catch (Exception e)
        return false;
share|improve this answer

Can you try to complete Context.PROVIDER_URL like this :

String ldapURL = "ldap://mdsdc3.example.com:389/DC=example,DC=com";

I Think it would be better to use GSSAPI, perhaps you can have a look here and here

share|improve this answer

Your Answer


