使用Java的LDAP认证

使用Java的LDAP认证

本文介绍了使用Java的LDAP认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为应用程序执行LDAP身份验证.

I need to do LDAP Authentication for an application.

我尝试了以下程序:

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, "[email protected]");
            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)

需要考虑的几点:

  1. 我以前使用的是tomcat 5.3.5,但是有人告诉我,只有tomcat 6支持它,因此我下载了tomcat 6.0.35,目前仅使用此版本.

  1. Earlier I was using tomcat 5.3.5 but somebody told me that only tomcat 6 supports it so I downloaded tomcat 6.0.35 and currently using this version only.

配置了server.xml并添加了以下代码-

Configured server.xml and added the following code -

<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"/> -->
    

  • 文章

    有人建议应该将某些jar文件复制到tomcat以便运行ldap身份验证,这是我需要做的吗?以及哪些jar文件?

    Someone suggested that there are some jar files that are supposed to be copied to tomcat in order to run ldap authentication, is that something I need to do? And which jar files?

    此外,我确定使用的凭据正确,那么是什么导致了此问题?

    Also, I am using the correct credentials for sure, then what is causing this issue?

    如果我使用不正确的属性,是否可以找到LDAP的正确属性?

    Is there a way I can figure out the correct attributes for LDAP in case I am using incorrect ones?

    推荐答案

    以下代码使用纯Java JNDI从LDAP进行身份验证.原理是:-

    Following Code authenticates from LDAP using pure Java JNDI. The Principle is:-

    1. 首先使用管理员或DN用户查找用户.
    2. 用户对象需要再次使用用户凭证
    3. 传递给LDAP.
    4. 没有异常意味着-已成功验证.其他身份验证失败.
    1. First Lookup the user using a admin or DN user.
    2. The user object needs to be passed to LDAP again with the user credential
    3. No Exception means - Authenticated Successfully. Else Authentication Failed.

    代码段

    public static boolean authenticateJndi(String username, String password) throws Exception{
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
        props.put(Context.SECURITY_PRINCIPAL, "uid=adminuser,ou=special users,o=xx.com");//adminuser - User with special priviledge, dn user
        props.put(Context.SECURITY_CREDENTIALS, "adminpassword");//dn user password
    
    
        InitialDirContext context = new InitialDirContext(props);
    
        SearchControls ctrls = new SearchControls();
        ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
        ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    
        NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
        javax.naming.directory.SearchResult result = answers.nextElement();
    
        String user = result.getNameInNamespace();
    
        try {
            props = new Properties();
            props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
            props.put(Context.SECURITY_PRINCIPAL, user);
            props.put(Context.SECURITY_CREDENTIALS, password);
    
       context = new InitialDirContext(props);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    

    这篇关于使用Java的LDAP认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 08-24 17:37