java集成微软的ad域,实现单点登录

时间:2024-03-10 16:25:17

1.ad域介绍:

windos server 2008R2服务器下的ad域,见下图(我是在虚拟机安装到windos server)

 

2.连接ad域代码:(里面代码自行修改)

public ResultMsg<User> loginAd(User user) throws Exception {
        ResultMsg<User> msg;
        //通过ad域登录
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        //ad域地址:windos server上输入ipconfig查看,369是固定端口,dc=contoso,dc=com是域的范围
        env.put(Context.PROVIDER_URL, "ldap://192.168.153.160:389/dc=contoso,dc=com");
        //ad域里面的用户
        env.put(Context.SECURITY_PRINCIPAL, "admin@contoso.com");
        //ad域里面的密码
        env.put(Context.SECURITY_CREDENTIALS, "Ai123456");
        DirContext ctx = null;
        NamingEnumeration results = null;
        User u1 = null;
        String st="";
        try {
            //登录验证
            ctx = new InitialDirContext(env);
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            //根据用户名查看ad域中是否存在当前用户
            results = ctx.search("", "(&(objectclass=person)(userprincipalname=" + user.getUsername()+domainName + "))", controls);
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            if (attributes != null) {
                //查询数据库用户
                User userByName = userService.getUserByName(user.getUsername());
                if(userByName==null)
                {
                    //设置唯一id
                    try {
                        for (NamingEnumeration ne=attributes.getAll();ne.hasMore();)
                        {
                            Attribute Attr = (Attribute) ne.next();
                            if ("objectGUID".equals(Attr.getID()))
                            {
                                st = DeptServiceImpl.getGUID(Attr.get().toString().getBytes());
                            }
                        }
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    //查询员工是否存在,若存在返回id编号不存在就插入
                    EmpBasic empBasicByUserPrincipalName = empMapper.getObjectGuid(st);
                    Integer integer;
                    if(empBasicByUserPrincipalName==null)
                    {
                        //添加员工
                        EmpBasic empBasic=new EmpBasic();
                        empBasic.setLastName(attributes.get("sn")==null?"":attributes.get("sn").get().toString());
                        empBasic.setFirstName(attributes.get("givenName")==null?"":attributes.get("givenName").get().toString());
                        empBasic.setNickName(attributes.get("displayname")==null?"":attributes.get("displayname").get().toString());
                        empBasic.setUserName(attributes.get("userprincipalname")==null?"":attributes.get("userprincipalname").get().toString().split("@")[0]);
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        empBasic.setHireDate(df.format(new Date()));
                        empBasic.setEmail(attributes.get("mail")==null?"":attributes.get("mail").get().toString());
                        empBasic.setCellphone(attributes.get("mobile")==null?"":attributes.get("mobile").get().toString());

                        empBasic.setObjectGuid(st);
                        String dateRq= attributes.get("whenCreated").get().toString().substring(0,8);
                        SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
                        Date date=df1.parse(dateRq);
                        empBasic.setHireDate(df.format(date));

                        //查询部门编号
                        String str = attributes.get("distinguishedName").get().toString().substring(
                                attributes.get("distinguishedName").get().toString().indexOf("O"));
                        Department department = deptMapper.getDistinguiName(str);
                        empBasic.setDeptNo(department.getDeptNo());
                        //返回插入的id
                        integer = empService.addAdEmp(empBasic);
                    }else
                        {
                            integer=empBasicByUserPrincipalName.getEmpNo();
                        }
                    //添加用户
                    User u = new User();
                    u.setUsername(attributes.get("userprincipalname").get().toString().split("@")[0]);
                    u.setLastName(attributes.get("sn")==null?"":attributes.get("sn").get().toString());
                    u.setFirstName(attributes.get("givenName")==null?"":attributes.get("givenName").get().toString());
                    u.setNickName(attributes.get("displayname")==null?"":attributes.get("displayname").get().toString());
                    u.setUserNo(integer.toString());
                    //添加用户时,用户类型默认为1,
                    u.setUserType(1);//?
                    //添加用户时,用户默认启用
                    u.setEnabled(1);
                    u.setIsAd(1);
                    userService.addAdUser(u);

                    u1= userService.getUserByName(u.getUsername());
                }else
                {
                    u1=userByName;
                    //查询部门
                    if (u1.getUserType().equals(1)) { //用户类型为员工时才查询其部门
                        u1.setDepartment(userService.getDeptInfoByUsername(user.getUsername()));
                    };
                }
            }
        } catch (AuthenticationException e) {
            String erroMsg=  e.getMessage();
            if (erroMsg.contains("701"))
            {
                msg = new ResultMsg<User>(false, "该账户已过期");
            }else if (erroMsg.contains("52e"))
            {
                msg = new ResultMsg<User>(false, "用户或密码错误");
            }else if (erroMsg.contains("525"))
            {
                msg = new ResultMsg<User>(false, "用户或密码错误");
            }else if (erroMsg.contains("773"))
            {
                msg = new ResultMsg<User>(false, "用户必须重置密码");
            } else if (erroMsg.contains("533"))
            {
                msg = new ResultMsg<User>(false, "用户账户禁用");
            }else
            {
                msg = new ResultMsg<User>(false, "用户登录失败");
            }
            return msg;
        } catch (NameNotFoundException e)//沒有对象
        {
            e.printStackTrace();
            msg = new ResultMsg<User>(false, "登录发生异常");
            return msg;
        } catch (NamingException e) {
            e.printStackTrace();
            msg = new ResultMsg<User>(false, "登录发生异常");
            return msg;
        } finally {
            if (results != null) {
                try {
                    results.close();
                } catch (Exception e) {
                }
            }
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception e) {
                }
            }
        }
        return msg = new ResultMsg<User>(true, "登录验证成功", "", u1);
    }
View Code