开发者

How can I just check if a given username exists?

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().开发者_JAVA技巧info("Authentication failed: " + a.getExplanation());

    }
    catch (NamingException e)
    {
        Logger.getLogger().info("Failed to bind to LDAP: " + e.getExplanation());
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜