JAVA 验证AD域名登陆

/**
     * 使用java连接AD域
     * @date 2015-1-26
     * @throws 异常说明
     * @param host 连接AD域服务器的IP
     * @param post AD域服务器的端口
     * @param username 用户名
     * @param password 密码
     * @return Integer 1 success 、0 false 、 -1 exception  
     */
    public static Integer connectAD(String host,String post,String username,String password) {
        DirContext ctx=null;
        int isLogin = 0;
        Hashtable<String,String> HashEnv = new Hashtable<String,String>();
        HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
        HashEnv.put(Context.SECURITY_PRINCIPAL, username!=null?username:""); //AD的用户名
        HashEnv.put(Context.SECURITY_CREDENTIALS, password!=null?password:""); //AD的密码
        HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); //LDAP工厂类
        HashEnv.put("com.sun.jndi.ldap.connect.timeout","3000");//连接超时设置为3秒
        HashEnv.put(Context.PROVIDER_URL," ldap://" + host + ":" + post);//默认端口389
        try {
        	if(password!=null&&!password.equals("")){
	            ctx = new InitialDirContext(HashEnv);//初始化上下文
	            //System.out.println("身份验证成功!");
	            isLogin = 1;
        	}else{
        		//System.out.println("身份验证失败!");
        		isLogin = 0;//没有输入密码属于身份失败
        	}
            
        } catch (AuthenticationException e) {
            //System.out.println("身份验证失败!");
            e.printStackTrace();
            isLogin = 0;
        } catch (javax.naming.CommunicationException e) {
            //System.out.println("AD域连接失败!");
            e.printStackTrace();
            isLogin = -1;
        } catch (Exception e) {
            //System.out.println("身份验证未知异常!");
            e.printStackTrace();
            isLogin = -1;
        } finally{
            if(null!=ctx){
                try {
                    ctx.close();
                    ctx=null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return isLogin;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值