1. 程式人生 > >ldap查詢、鑒權

ldap查詢、鑒權

toe out col jndi authent scope vid ini add

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 = "(&(|(|([email protected]
/* */)([email protected]))(|([email protected])([email protected])))(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 = "(|([email protected])([email protected]))";// 要鑒權的用戶
            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查詢、鑒權