码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA windows 域认证指南

时间:2015-03-06 12:53:25      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:

实现方法:

import java.util.Hashtable;

import javax.naming.Context;

import javax.naming.NamingEnumeration;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;


public class LdapAuth {

        

         private String domain;

         private String ldapHost;

         private String searchBase;

        

         public LdapAuth(){

                   this.domain = "{域}";

                   this.ldapHost = "ldap://{IP}:{端口}";

                   this.searchBase = "DC={DC},DC={DC}";

         }

        

         public LdapAuth(String domain,String host,String dn){

                   this.domain = domain;

                   this.ldapHost = host;

                   this.searchBase = dn;

         }

        

         public boolean authLdap(String username,String pass){

                  

                   String searchFilter = "(&(objectClass=user)(sAMAccountName=" + username + "))";

                   Hashtable env = new Hashtable();

                  

                   env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

                  

                   env.put(Context.PROVIDER_URL, ldapHost);

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, username + "@" + domain);

        env.put(Context.SECURITY_CREDENTIALS, pass);

       

        LdapContext ctxGC = null;

        boolean ldapUser = false;

        try {

                            ctxGC = new InitialLdapContext(env,null);

                            NamingEnumeration answer = ctxGC.search(searchBase, searchFilter,null);

                           

                            if (answer!=null) {

                                     ldapUser = true;

                            }

                   } catch (Exception e) {

                            // TODO: handle exception

                   }

                  

                   return ldapUser;

         }

测试:

用户名密码正确:

 

用户名密码错误:

 


JAVA windows 域认证指南

标签:

原文地址:http://my.oschina.net/u/1162040/blog/383335

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