LdapTemplate+springBoot

使用LdapTemplate自己的封装方法进行Ldap数据库的CRUD

  • maven依赖
	
			org.springframework.boot
			spring-boot-starter-data-ldap
	
  • 连接配置及LdapTemplate生成
spring.ldap.urls: ldap://ip:port
spring.ldap.base: dc=hadoop,dc=com
spring.ldap.username: cn=Manager,dc=hadoop,dc=com
spring.ldap.password: 密码
  • 添加组和用户类
    在这里插入图片描述

  • 测试

  1. 创建组
public void createGroup(String group)throws Exception{
        try {
            LdapGroup g = new LdapGroup(group);
            g.setGidNumber(sysDictService.getNextLinuxGid());
            ldapTemplate.create(g);
        }catch (NameAlreadyBoundException e){
            log.error(e.getMessage(),e);
            throw new BusinessException(ErrorCode.CODE_ERROR,"用户组 [" + group + "] 已经存在");
        }
    }
  1. 创建用户
  public LdapUser createUser(String userName)throws Exception{
        try {

            LdapUser user = new LdapUser(userName);
            user.setUidNumber(sysDictService.getNextLinuxUid());
            String pwd = user.getUserPassword();
            BASE64Encoder base64en = new BASE64Encoder();
            String md5psw = base64en.encode(MD5Util.encodeByte(pwd));
            user.setUserPassword("{MD5}"+md5psw);
            ldapTemplate.create(user);
            user.setUserPassword(pwd);
            return user;
        }catch (NameAlreadyBoundException e){
            log.error(e.getMessage(),e);
            throw new BusinessException(ErrorCode.CODE_ERROR,"用户 [" + userName + "] 已经存在");
        }
    }
  1. 添加用户到组
 public void addUserToGroup(String group,String userName)throws Exception{
        try{
            LdapGroup u =  ldapTemplate.findOne(query().where("cn").is(group),LdapGroup.class);
            u.getMemberUid().add(userName);
            ldapTemplate.update(u);
        }catch (EmptyResultDataAccessException e){
            log.error(e.getMessage(),e);
            throw new BusinessException(ErrorCode.CODE_ERROR,"用户组 [" + group + "] 不存在");
        }
    }

你可能感兴趣的:(权限)