当前位置: 代码迷 >> Java Web开发 >> java 查询 AD 报错,请高手解决,该如何解决
  详细解决方案

java 查询 AD 报错,请高手解决,该如何解决

热度:759   发布时间:2016-04-17 10:15:20.0
java 查询 AD 报错,请高手解决,急急急急
小弟最近在做一个系统的登录验证,要求从Windows 的 AD中验证,登录名为AD中的sAMAccountName的值,自己配了一台服务器,验证是没有问题的,但访问正式服务器时却抛出异常,请教各位高手,代码如下;

import java.util.Hashtable;
import java.util.List;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;

/**
* 验证用户登录
* @throws NamingException 
*/
public String validateLogin() throws AMSException, NamingException {

String flag = "";
String responseMsg = "";
// 获取用户名,密码
String userName = this.getParameter("userName");

String password = this.getParameter("password");

String verifyCode = this.getParameter("verifyCode");// 文本框填写的验证码

Control[] connCtls = null;
  
String userDN = "";
 
if(null==userName){
flag = "login";
responseMsg = "1";
}else if(null==password){
flag = "login";
responseMsg = "2";
}else if(null==verifyCode){
flag = "login";
responseMsg = "3";
}else{

ServletActionContext.getRequest().setAttribute("userName", userName);
verifyCode = verifyCode.toLowerCase();

AcitiveDirectoryConfig adConfig =new AcitiveDirectoryConfig();

//activedirectory ip
String activedirectoryIP=adConfig.getADConifg("AD_IP");

//activedirectory port
String activedirectoryPort=adConfig.getADConifg("AD_PORT");

String activedirectoryRoot=adConfig.getADConifg("AD_ROOT");

String verifyCodeConfirm=ServletActionContext.getRequest().getSession().getAttribute("random").toString();//servlet生成的验证码

String ad_username = adConfig.getADConifg("AD_USERNAME");

String ad_bindpassword = adConfig.getADConifg("AD_BINDPASSWORD");

Hashtable<String, String> env = new Hashtable<String, String>();

DirContext ctx;


env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
 
env.put(Context.PROVIDER_URL, "ldap://"+activedirectoryIP+":"+activedirectoryPort+"/"+activedirectoryRoot);//LDAP server
 
env.put(Context.SECURITY_AUTHENTICATION, "simple");

env.put(Context.SECURITY_PRINCIPAL, ad_username); 

env.put(Context.SECURITY_CREDENTIALS, ad_bindpassword);

try{
ctx = new InitialLdapContext(env,connCtls);
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
System.out.println("*************************");
NamingEnumeration en = ctx.search("", "sAMAccountName="+userName, constraints);---就这句报异常  
ctx.close();
if(en == null){
flag = "login";
responseMsg = "4";
System.out.println("11111111");
}
if(!en.hasMoreElements()){
flag = "login";
responseMsg = "4";
System.out.println("222222222222");
}else{
while (en != null && en.hasMoreElements()){//maybe more than one element
  相关解决方案