使用Spring的LdapTemplate进行LDAP操作

使用Spring的LdapTemplate进行LDAP操作

<!-- 日志内容 -->

      最近利用空闲时间研究了一把LDAP,然后用spring进行了一些编程尝试,通过spring的LdapTemplate可以很方便的进行LDAP的CRUD操作。如果你不清楚啥是LDAP的话,可以查询相关资料后再看此文。一般来说LDAP可以用来作为一个用户中心,围绕LDAP可以部署一些应用来共享相同的账号,这个在企业管理中是非常有帮助的,因为企业的内部应用可能是几个到几十个,员工如果有统一的账号密码,那将非常方便。

      我也是因为内部需要,围绕LDAP做了一些应用集成,使用的LDAP服务器是apache的DS,标准的LDAP协议,客户端编程用java,使用spring的LdapTemplate类进行操作。使用maven管理的话,在项目中加入如下依赖:

    

<dependency>
    <groupId>com.sun</groupId>

    <artifactId>ldapbp</artifactId>

    <version>1.0</version>

</dependency>
<dependency>
    <groupId>org.springframework</groupId>

    <artifactId>spring-ldap</artifactId>

    <version>1.1.2</version>

</dependency>

 

   然后就可以使用LDAP进行操作了,当然了也要加入其它的spring对应的包,比如core包等,下面分别说明使用spring的LdapTemplate如何进行操作。注意,在应用之前请先配置好apache-DS服务(请参考文章xxx)。 

 

    1、初始化LdapTemplate
private static final LdapTemplate template;

 

static {

    LdapContextSource cs = new LdapContextSource();

    cs.setCacheEnvironmentProperties(false);

    cs.setUrl("ldap://192.168.1.188:10389");

    cs.setBase("dc=mzone,dc=cc");

    cs.setAuthenticationSource(new AuthenticationSource() {

        @Override
	public String getCredentials() {

	    return "mzonecc";

	}

 
	@Override
	public String getPrincipal() {

	    return "uid=admin,ou=system";

	}

    });

    template = new LdapTemplate(cs);

}
 

      初始化时主要是设置连接地址、基础目录(我们这里是dc=mzone,dc=cc)和认证信息(包括账号和密码)。注意认证信息中getCredentials返回的是密码信息,而getPrincipal方法返回的是账号DN(基于基础目录)。

2、查询(搜索)

      查询在LdapTemplate中是search说法,相关代码如下:

  

public User getUserById(String uid) {

    String filter = "(&(objectclass=inetOrgPerson)(uid=" + uid + "))";

    List<User> list = template.search("ou=rd", filter, new AttributesMapper() {

        @Override
	public Object mapFromAttributes(Attributes attributes) throws NamingException {

	    User user = new User();

 
            Attribute a = attributes.get("cn");

            if (a != null) user.setRealname((String)a.get());

 
            a = attributes.get("uid");

            if (a != null) user.setUsername((String)a.get());

 
            return user;

	}

    });

    if (list.isEmpty()) return null;

    return list.get(0);

}

 

      首先我们要构造一个filter,即search方法的第2个参数,这个filter是标准的LDAP查询过滤器,可以参考下LDAP的filter写法相关文档。

 

3、添加

 

public boolean addUser(User vo) {

    try {

        // 基类设置

	BasicAttribute ocattr = new BasicAttribute("objectClass");

	ocattr.add("top");

	ocattr.add("person");

	ocattr.add("uidObject");

	ocattr.add("inetOrgPerson");

	ocattr.add("organizationalPerson");

	// 用户属性

	Attributes attrs = new BasicAttributes();

	attrs.put(ocattr);

	attrs.put("cn", StringUtils.trimToEmpty(vo.getRealname()));

	attrs.put("sn", StringUtils.trimToEmpty(vo.getUsername()));

	attrs.put("displayName", StringUtils.trimToEmpty(vo.getRealname()));

	attrs.put("mail", StringUtils.trimToEmpty(vo.getEmail()));

	attrs.put("telephoneNumber", StringUtils.trimToEmpty(vo.getMobile()));

	attrs.put("title", StringUtils.trimToEmpty(vo.getTitle()));

	attrs.put("userPassword", StringUtils.trimToEmpty(vo.getPassword()));

	template.bind("uid=" + vo.getUsername().trim(), null, attrs);

	return true;

    } catch (Exception ex) {

	ex.printStackTrace();

	return false;

    }

}

 

 

  1. 在LDAP中是没有添加这一说法的,标准的叫法是绑定,对应的删除就是解绑。绑定时要将所有必须属性都添加上,首先是objectClass属性,这个是LDAP中的对象,LDAP中的对象是继承的,每个对象都有一些特定的属性,有些属性是必须的,有些是可选的。第2个步骤就是将每个对象的必须属性和你想要的非必须属性填上交由LdapTemplate进行绑定即可。

 

 

      4、更新

     

public boolean updateUser(User vo) {

    try {

	template.modifyAttributes("uid=" + vo.getUsername().trim(), new ModificationItem[] {

	    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("cn", vo.getRealname().trim())),
	    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("displayName", vo.getRealname().trim())),
	    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("sn", vo.getUsername().trim())),
	    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("mail", vo.getEmail().trim())),
	    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("telephoneNumber", vo.getMobile().trim())),
	    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("title", vo.getTitle().trim()))

	});

	return true;

    } catch (Exception ex) {

	ex.printStackTrace();

	return false;

    }

}

 

 

  1. 更新就是替换属性,使用ModificationItem类进行处理。

 

     5、删除

   

public boolean deleteUser(String username) {

    try {

	template.unbind("uid=" + username.trim());

	return true;

    } catch (Exception ex) {

	ex.printStackTrace();

	return false;

    }

}

 

 

 
   
  1. 删除也就是解绑的过程,直接调用unbind即可。

 

     

      上面几个操作基本上就覆盖了LDAP的基本操作,对于查询可能更多的是要注意如何些filter,增加要确定objectClass。另外,如果在初始化LdapContextSource时设置了base,那么后面的LdapTemplate中所有的操作DN都是基于改base构建而成的全路径,这个要注意。其他来说,看看代码就知道怎么回事了,相对比较简单。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用Spring LDAP进行账号禁用的程序: 1. 首先需要在pom.xml中添加Spring LDAPSpring Security的依赖: ```xml <dependencies> <!-- Spring LDAP --> <dependency> <groupId>org.springframework.ldap</groupId> <artifactId>spring-ldap-core</artifactId> <version>2.3.3.RELEASE</version> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-ldap</artifactId> <version>5.5.0</version> </dependency> </dependencies> ``` 2. 配置LDAP连接信息 ```java @Configuration public class LdapConfig { @Value("${ldap.url}") private String url; @Value("${ldap.base}") private String base; @Value("${ldap.username}") private String username; @Value("${ldap.password}") private String password; @Bean public LdapContextSource contextSource() { LdapContextSource contextSource = new LdapContextSource(); contextSource.setUrl(url); contextSource.setBase(base); contextSource.setUserDn(username); contextSource.setPassword(password); return contextSource; } } ``` 3. 编写LdapAccountService类 ```java @Service public class LdapAccountService { private final LdapTemplate ldapTemplate; public LdapAccountService(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; } /** * 禁用LDAP账号 * * @param username 用户名 * @return 禁用结果 */ public boolean disableAccount(String username) { // 查询用户Dn String userDn = getUserDn(username); if (StringUtils.isEmpty(userDn)) { return false; } // 设置用户状态为禁用 ModificationItem[] modificationItems = new ModificationItem[]{ new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", "514")) }; try { ldapTemplate.modifyAttributes(userDn, modificationItems); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 查询用户Dn * * @param username 用户名 * @return 用户Dn */ public String getUserDn(String username) { String filter = "(&(objectClass=user)(sAMAccountName=" + username + "))"; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); List<String> result = ldapTemplate.search("", filter, searchControls, (Attributes attributes) -> attributes.get("distinguishedName").get().toString() ); return result.isEmpty() ? null : result.get(0); } } ``` 4. 在Controller中调用LdapAccountService进行账号禁用 ```java @RestController public class AccountController { private final LdapAccountService ldapAccountService; public AccountController(LdapAccountService ldapAccountService) { this.ldapAccountService = ldapAccountService; } @PostMapping("/disableAccount") public ResponseEntity<String> disableAccount(@RequestParam String username) { boolean result = ldapAccountService.disableAccount(username); return result ? ResponseEntity.ok("账号禁用成功") : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("账号禁用失败"); } } ``` 以上就是使用Spring LDAP进行账号禁用的程序,希望能够帮到你。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值