如何仅检查特定用户名是否存在?

5
我有一个应用程序,使用LDAP和简单的数据库认证来登录用户。只有当用户不存在于LDAP上下文中时,应用程序才会检查他是否存在于数据库中。因此,我需要一种方法,在不知道密码的情况下检查用户是否存在于LDAP中。我提到过用户名是唯一的。
我使用以下代码,如果我有正确的用户名和密码,则有效。如果密码或用户名错误,我会收到异常。如果可以得到不同的异常,一个表示用户名不存在,另一个表示提供的密码错误,那将是理想的。
    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());
    }
1个回答

3

您正在使用用户名称在LDAP中搜索用户。但是要进行LDAP身份验证,您还需要使用搜索的用户名和密码。

只需使用另一个(管理员)用户和密码进行身份验证,并在搜索到用户后返回true。


谢谢。这是唯一的方法吗?必须登录才能进行搜索吗? - radonys
也许不需要,我不确定。我只是在解释为什么你的代码需要用户密码来检查它是否存在于LDAP中。 - JB Nizet
1
有些管理员会允许匿名搜索。请与您的目录服务器管理员确认。 - Terry Gardner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接