Search code examples
ldapopenldapldap-query

How to connect LDAP With username and password?


I have my Ldap working the only issue i'm facing was when I try to login with email that is when I land in the else part in the below code. If my username is different from email then it throws error. i.e if my email is '[email protected]' and my username is 'saurakumar' then it will through invalid username password error. As internally I'm using username to make email i.e if the user login with name 'karan' then i'm expecting the email to be karan @gmail.com which is not true in many scenario and the Authentication fails. I'm looking for some solution wherein I can login either via email or via username I'll be able to authenticate user. Below is the snippet of my code. Please suggest?

    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    ldapEnv.put(Context.PROVIDER_URL, url);
    ldapEnv.remove(Context.SECURITY_PROTOCOL);
    if (email == null) {
        lContext = new InitialLdapContext(ldapEnv, null);
        entryResult = searchUserEntry(lContext, user, searchCtrls);
        final String usrDN = ((Context) entryResult.getObject()).getNameInNamespace();

        lContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
        lContext.addToEnvironment(Context.SECURITY_PRINCIPAL, usrDN);
        lContext.addToEnvironment(Context.SECURITY_CREDENTIALS, pass);
        lContext.reconnect(null);
    } else {
            ldapEnv.put(Context.SECURITY_PRINCIPAL, email);
            ldapEnv.put(Context.SECURITY_CREDENTIALS, credentials);
            lContext = new InitialLdapContext(ldapEnv, null);
            return lContext;
        searchUserEntry(lContext, user, searchCtrls);
    }

Solution

  • Normally this is a 3-step process:

    1. Bind to LDAP as an administrative user. Note that this should not be the master user defined in the configuration file: that's for OpenLDAP's use itself. Instead it should be a user mentioned in the DIT that has the appropriate search access for the next step.

    2. Search for the user via some unique attribute, e.g. in your case email.

    3. Using the found DN of the user and the password he specified, attempt to bind as that user (with the reconnect() method, after changing the environment of the context appropriately).

    If all that succeeds, you have a login success. If (2) or (3) fail, you have a failure, and note that you should not tell the user which it was: otherwise you are leaking information to attackers. You should not mention whether it was the username (email) or the password that was wrong.