Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I just check if a given username exists?

Tags:

java

ldap

I have an application that uses both LDAP and simple database authentication to log users in. Only if the user does not exists in the LDAP context, the application checks if he exists in the database. So I need a way to check if the users exists in LDAP, without knowing the password. I mention that usernames are unique.

I use this code, which works if I have a correct username and password. If the password OR the username are wrong, I get an exception. It would be ideal if I could get different exceptions, one if the username does not exist, other if the password provided is wrong.

    String username = "test";
    String password = "pass";
    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, "ldap://server.example.com:389");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");
    String user = username + "@example.com";
    environment.put(Context.SECURITY_PRINCIPAL, user ); 
    environment.put(Context.SECURITY_CREDENTIALS, password);
    try
    {
        DirContext context = new InitialDirContext(environment);

        String searchBase = "DC=server,DC=example,DC=COM";
        String FILTER = "(&(objectClass=user)(objectCategory=person)((sAMAccountName=" + username + ")))";
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> answer = context.search(searchBase, FILTER, ctls);
        SearchResult result = answer.next();
        Attribute email = result.getAttributes().get("mail");
        Attribute cn = result.getAttributes().get("cn");
        System.out.println(cn + " : " + email);
        context.close();
    }
    catch (AuthenticationException a)
    {
        Logger.getLogger().info("Authentication failed: " + a.getExplanation());

    }
    catch (NamingException e)
    {
        Logger.getLogger().info("Failed to bind to LDAP: " + e.getExplanation());
    }
like image 394
radonys Avatar asked Oct 24 '22 23:10

radonys


1 Answers

You're searching for a user in the LDAP, using only his user name. But to authenticate to the LDAP, you're using the searched user name and his password.

Just use another (admin) user and password to authenticate, and return true if the search for the user returns something.

like image 91
JB Nizet Avatar answered Oct 31 '22 14:10

JB Nizet