我正在尝试使用LDAP通过Windows Active Directory进行身份验证。我有一个LDAPContext类来设置上下文,还有一个authenticate方法,可以在AD中查找电子邮件地址。
这是我的LDAPContext类:
public class LDAPContext extends InitialDirContext {
Hashtable<String, String> env = new Hashtable<String, String>();
public LDAPContext(String email, String password) throws NamingException
{
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://myintranet.com");
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,"mail="+email+"\""); // specify the username
env.put(Context.SECURITY_CREDENTIALS,password);
DirContext ctx = new InitialDirContext(env);
}
}
这是我的认证方法:
public static User authenticate(final String email, final String password){
try {
LDAPContext adContext = new LDAPContext(email, password);
Attributes matchAttrs = new BasicAttributes(true);
matchAttrs.put(new BasicAttribute("mail", email));
NamingEnumeration<SearchResult> en = adContext.search("", matchAttrs);
while(en.hasMore()) {
System.out.println("Found email!!!");
}
} catch(NamingException e) {
System.out.println("NamingException");
}
...
我一直收到“NamingException”错误。我确定电子邮件在AD中,并且指定的电子邮件名称为“mail”。我做错了什么?
编辑:这是我收到的具体错误:
javax.naming.AuthenticationException:[LDAP:error code 49 - 80090308:LdapErr:DSID-0C0903A9,comment:AcceptSecurityContext error,data 52e,v1db1]
这意味着凭据不正确。我已经尝试硬编码,但仍然无法正常工作。
javax.naming.NotContextException: Not an instance of DirContext
我尝试过在谷歌上搜索,但找不到解决方案。你有什么想法吗? - Kungenenv.put(Context.REFERRAL, "follow");
,现在我不再收到任何异常。 - KungenNotContextException
通常表示您添加到HashTable
的属性存在问题,但在我看来,将REFERRAL
设置为follow
不应该解决该问题。无论如何,很高兴现在它能工作了。 - Syonusername@domain
这个问题。但是当我修复它后,出现了NotContextException
错误,而设置REFFERAL解决了这个问题。好的,既然你的回答是解决方案的一部分,我会接受它的。谢谢! - Kungen