JAVA 验证AD域名登陆

来源:互联网 发布:js点击选中再点击取消 编辑:程序博客网 时间:2024/05/17 23:06
/**     * 使用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
原创粉丝点击