码迷,mamicode.com
首页 > 其他好文 > 详细

ldap查询、鉴权

时间:2017-08-08 19:53:12      阅读:389      评论:0      收藏:0      [点我收藏+]

标签:red   on()   app   gets   str   conf   constrain   objectc   roo   

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查询、鉴权

标签:red   on()   app   gets   str   conf   constrain   objectc   roo   

原文地址:http://www.cnblogs.com/linying/p/7308146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!