我有一个使用LDAP和简单数据库身份验证的应用程序来记录用户.只有当用户在LDAP上下文中不存在时,应用程序才会检查他是否存在于数据库中.所以我需要一种方法来检查用户是否存在于LDAP中,而不知道密码.我提到用户名是唯一的.
我使用此代码,如果我有正确的用户名和密码,它可以工作.如果密码或用户名错误,我会得到一个例外.如果我能得到不同的例外,那将是理想的,如果用户名不存在,则为1,如果提供的密码错误则为其他例外.
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());
}
Run Code Online (Sandbox Code Playgroud)
您正在 LDAP 中搜索用户,仅使用他的用户名。但要对 LDAP 进行身份验证,您需要使用搜索到的用户名及其密码。
只需使用另一个(管理员)用户和密码进行身份验证,如果搜索用户返回某些内容,则返回 true。
| 归档时间: |
|
| 查看次数: |
9004 次 |
| 最近记录: |