使用 Java 的 LDAP 身份验证
我需要为应用程序执行 LDAP 身份验证。
我尝试了以下程序:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapContextCreation {
public static void main(String[] args) {
LdapContextCreation ldapContxCrtn = new LdapContextCreation();
LdapContext ctx = ldapContxCrtn.getLdapContext();
}
public LdapContext getLdapContext(){
LdapContext ctx = null;
try{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
//it can be <domain\\userid> something that you use for windows login
//it can also be
env.put(Context.SECURITY_PRINCIPAL, "username@domain.com");
env.put(Context.SECURITY_CREDENTIALS, "password");
//in following property we specify ldap protocol and connection url.
//generally the port is 389
env.put(Context.PROVIDER_URL, "ldap://server.domain.com");
ctx = new InitialLdapContext(env, null);
System.out.println("Connection Successful.");
}catch(NamingException nex){
System.out.println("LDAP Connection: FAILED");
nex.printStackTrace();
}
return ctx;
}
}
获取以下异常:
LDAP Connection: FAILED
javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3053)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2999)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2801)
at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2715)
at com.sun.jndi.ldap.LdapCtx.(LdapCtx.java:305)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:187)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:205)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:148)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:78)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:235)
at javax.naming.InitialContext.initializeDefaultInitCtx(InitialContext.java:318)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:348)
at javax.naming.InitialContext.internalInit(InitialContext.java:286)
at javax.naming.InitialContext.init(InitialContext.java:308)
at javax.naming.ldap.InitialLdapContext.(InitialLdapContext.java:99)
at LdapContextCreation.getLdapContext(LdapContextCreation.java:27)
at LdapContextCreation.main(LdapContextCreation.java:12)
还有几点需要考虑:
早些时候我正在使用,但有人告诉我只有tomcat 6支持它,所以我下载并目前只使用此版本。
tomcat 5.3.5tomcat 6.0.35-
已配置并添加了以下代码 -
server.xml<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99" connectionURL="ldap://server.domain.com:389/" userPattern="{0}" /> -
注释以下代码来自
server.xml-<!-- Commenting for LDAP <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> --> 文章中的步骤 2 和 3
有人建议有一些jar文件应该复制到tomcat才能运行身份验证,这是我需要做的事情吗?哪些文件?
ldapjar另外,我肯定使用正确的凭据,那么导致此问题的原因是什么?
有没有办法找出LDAP的正确属性,以防我使用不正确的属性?