LDAP: error code 49 - Simple Bind Failed: NT_STATUS_LOGON_FAILURE

rahul picture rahul · Mar 13, 2014 · Viewed 9.4k times · Source

I am trying to authenticate the user but it throws Exception.May be there is problem in configuration.

public class LdapApplication {
private static final String INITIAL_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private static final String SECURITY_AUTHENTICATION ="simple";
private static final String NAMED_CONTEXT = "CN=Users";
private static final String SAM_ACCOUNT_NAME = "sAMAccountName=";

public static void main(String[] args) {

    Hashtable env = new Hashtable();

    env.put(Context.INITIAL_CONTEXT_FACTORY,INITIAL_CONTEXT_FACTORY);
    env.put(Context.PROVIDER_URL, "ldap://ip:portNo/dc=organisation,dc=in");
    env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
    env.put(Context.SECURITY_PRINCIPAL, "cn=userName,cn=Users");
    env.put(Context.SECURITY_CREDENTIALS, "password" );
    DirContext context = null;

    NamingEnumeration namingEnumeration = null;
    try {
        context = new InitialDirContext(env);

        namingEnumeration = context.search(NAMED_CONTEXT, SAM_ACCOUNT_NAME+ userName, null);
        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = (SearchResult) namingEnumeration.next();
            Attributes attributes = searchResult.getAttributes();

            System.out.println(" Person Common Name = " + attributes.get("cn"));
          System.out.println(" Person Display Name = " + attributes.get("displayName"));

            }catch(Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();

            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (Exception e) {
            }
        }
        if (context != null) {
            try {
                context.close();
            } catch (Exception e) {
            }
        }
    }

}

}

but if i mention Context.SECURITY_PRINCIPAL as "organisation\\userName" instead of "cn=userName,cn=Users" it works perfectly fine. Kindly suggest a possible solution because my requirement is to give SECURITY_PRINCIPAL something using cn or dc.

Answer

mvreijn picture mvreijn · Mar 13, 2014

You are using a relative distinguished name which will not work.

Change your code to use

env.put(Context.SECURITY_PRINCIPAL, "cn=userName,cn=Users,dc=organisation,dc=in");

and also change your search context to:

private static final String NAMED_CONTEXT = "CN=Users,dc=organisation,dc=in";

Always use full distinguished names with LDAP.