首页 > 代码库 > ldap查询、鉴权

ldap查询、鉴权

package cn.richinfo.ldap;

import java.util.Iterator;

import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPSearchResults;

public class LdapSearch {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        //String ldapHost = "116.62.8.139";// ldap服务器
        String ldapHost = "192.168.34.97";
        int ldapPort = LDAPConnection.DEFAULT_PORT;// ldap端口
        String loginDN = "cn=Directory Manager,o=h3gat";// rootdn(slapd.conf的rootdn属性)
        String password = "123456";// rootpw(slapd.conf的rootpw属性)
        String searchBase = "o=h3gat";// suffix(slapd.conf的suffix属性)
        int searchScope = LDAPConnection.SCOPE_SUB;// 查询范围
        String searchFilter = "objectClass=*";//查询zteperson所有用户
        //String searchFilter = "(&(|(|(mail=gay4@richmail.com)(mail=aaa@richinfo.cn))(|(mailalternateaddress=gay4@richmail.com)(mailalternateaddress=aaa@richinfo.cn)))(blocked=0))";// filter

        LDAPConnection lc = new LDAPConnection();
        try {
            lc.connect(ldapHost, ldapPort);
            lc.bind(LDAPConnection.LDAP_V3, loginDN, password.getBytes("UTF8"));
            System.out.println("Bind success.");
            LDAPSearchResults searchResults = lc.search(searchBase, searchScope, searchFilter, null, false);
            System.out.println("Result = " + searchResults.getCount());
            while (searchResults.hasMore()) {
                LDAPEntry nextEntry = null;
                try {
                    nextEntry = searchResults.next();
                } catch (LDAPException e) {
                    System.out.println("Error: " + e.toString());
                    if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR) {
                        break;
                    } else {
                        continue;
                    }
                }
                System.out.println("DN = " + nextEntry.getDN());
                System.out.println("\tAttributes list:");
                LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
                Iterator<LDAPAttribute> allAttributes = attributeSet.iterator();
                while (allAttributes.hasNext()) {
                    LDAPAttribute attribute = allAttributes.next();
                    System.out.println("\t\t" + attribute.getName() + " = " + attribute.getStringValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (lc.isConnected()) {
                    lc.disconnect();
                    System.out.println("Unbind success.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

package cn.richinfo.ldap;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class LdapAuthentication {

    private LdapContext ctx = null;
    private final Control[] connCtls = null;

    private void execute() {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");// 不用改
        env.put(Context.PROVIDER_URL, "ldap://116.62.8.139:389/");// ldap服务器
        env.put(Context.SECURITY_AUTHENTICATION, "simple");// 不用改
        env.put(Context.SECURITY_CREDENTIALS, "123456");// rootpw(slapd.conf的rootpw属性)
        env.put(Context.SECURITY_PRINCIPAL, "cn=Directory Manager,o=h3gat"); // rootdn(slapd.conf的rootdn属性)

        try {
            ctx = new InitialLdapContext(env, connCtls);
            System.out.println("Bind success.");
            String suffix = "o=h3gat";// suffix(slapd.conf的suffix属性)
            String filter = "(|(mail=gay5@richmail.com)(mailalternateaddress=gay5@richinfo.cn))";// 要鉴权的用户
            String password = "83B34499282F00DFDB908238435026C2";// //要鉴权的用户密码
            authenricate(suffix, filter, password);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                    System.out.println("Unbind success.");
                } catch (NamingException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public static void main(String[] args) {
        LdapAuthentication ldap = new LdapAuthentication();
        ldap.execute();
    }

    private String getUserDN(String suffix, String filter) {
        String userDN = "";
        try {
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> en = ctx.search(suffix, filter, constraints);
            if (en == null || !en.hasMoreElements()) {
                System.out.println("未找到该用户");
            }
            while (en.hasMoreElements()) {
                SearchResult result = en.nextElement();
                System.out.println(result.getNameInNamespace());
                userDN = result.getNameInNamespace();
            }
        } catch (Exception e) {
            System.out.println("查找用户时产生异常。");
            e.printStackTrace();
        }

        return userDN;
    }

    public boolean authenricate(String suffix, String filter, String password) {
        boolean valide = false;
        try {
            String userDN = getUserDN(suffix, filter);
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            ctx.reconnect(connCtls);
            System.out.println("Authenricate success.");
            valide = true;
        } catch (Exception e) {
            e.printStackTrace();
            valide = false;
        }
        return valide;
    }

}

 

ldap查询、鉴权