`
aa00aa00
  • 浏览: 325165 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
文章分类
社区版块
存档分类
最新评论

JAVA 实现AD验证

 
阅读更多

package com.wanda.sso.client.servlet;

import java.util.HashMap;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 * *
 *
 * @author winter *
 */
public class AdTools {

 /**
  * AD 验证
  *
  * @param userName
  * @param passWord
  * @return
  */
 public static boolean adTrueOrFalse(String userName, String passWord) {
  String url = new String("ldap://" + SsoClientUtils.AD_SERVER_IP + ":"
    + SsoClientUtils.AD_SERVER_PORT);
  String user = userName.indexOf(SsoClientUtils.AD_SERVER_DOMAIN) > 0 ? userName
    : userName + SsoClientUtils.AD_SERVER_DOMAIN;
  Hashtable env = new Hashtable();
  DirContext ctx;
  env.put(Context.SECURITY_AUTHENTICATION, "simple");
  env.put(Context.SECURITY_PRINCIPAL, user);
  env.put(Context.SECURITY_CREDENTIALS, passWord);
  env.put(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, url);
  try {
   ctx = new InitialDirContext(env);
   ctx.close();
   // System.out.println("验证成功!");
   return true;
  } catch (NamingException err) {
   err.printStackTrace();
   // System.out.println("验证失败!");
   return false;
  }
 }

 // 使用LDAP验证密码
 public static void main(String[] args) {
  String userName = "xueqiang"; // 用户名称
  String passwd = "123456";
  String host = "10.0.4.26"; // AD服务器
  String port = "389"; // 端口
  String domain = "@wanda-dev.cn"; // 邮箱的后缀名
  String url = new String("ldap://" + host + ":" + port);
  String user = userName.indexOf(domain) > 0 ? userName : userName
    + domain;
  Hashtable<String, String> env = new Hashtable<String ,String>();
  DirContext ctx = null;
  env.put(Context.SECURITY_AUTHENTICATION, "simple");
  env.put(Context.SECURITY_PRINCIPAL, user);
  if ("".equals(passwd.trim())) {
   passwd = null;
   System.out.println("密码不能为空!!");
  }
  env.put(Context.SECURITY_CREDENTIALS, passwd);
  env.put(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
  env.put(Context.PROVIDER_URL, url);
  try {
   ctx = new InitialDirContext(env);
   ctx.close();
   System.out.println("验证成功!!");
  } catch (NamingException e) {
   e.printStackTrace();
   System.out.print("验证失败!!");
  }
 }
}

分享到:
评论
1 楼 huahoucun 2014-04-11  
passwd = null;
env.put(Context.SECURITY_CREDENTIALS, passwd);
  env.put(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
  env.put(Context.PROVIDER_URL, url);
  try {
   ctx = new InitialDirContext(env);
   ctx.close();
   System.out.println("验证成功!!");
  } catch (NamingException e) {
   e.printStackTrace();
   System.out.print("验证失败!!");
  }
passwd 为 null 时去域里头验证 能否通过呢?

相关推荐

Global site tag (gtag.js) - Google Analytics