一.安装
拉取镜像
docker pull osixia/openldap
运行镜像
docker run \
-p 389:389 \
-p 636:636 \
--restart=always \
--name myopenldap \
--network bridge \
--hostname openldap-host \
--env LDAP_TLS_VERIFY_CLIENT="never" \
--env LDAP_ORGANISATION="myLdap" \
--env LDAP_DOMAIN="myLdap.com" \
--env LDAP_ADMIN_PASSWORD="myLdap123" \
-v /data/ldap/data:/var/lib/ldap \
-v /data/ldap/conf:/etc/ldap/slapd.d \
--detach osixia/openldap
使用LDAP admin来连接;
base 为:dc=myLdap,dc=com
username:cn=admin,dc=myLdap,dc=com
password:myLdap123
如果连不上,就把容器删除,重新run一下
代码
配置连接信息
server:
port: 8080
spring:
ldap:
urls: ldap://xxxx:389
base: dc=myLdap,dc=com
username: cn=admin,dc=myLdap,dc=com
password: myLdap123
pom文件增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
<version>2.7.0</version>
</dependency>
定义实体user对象
@Data
@Entry(base = "ou=people,dc=myLdap,dc=com", objectClasses = "inetOrgPerson")
public class User {
@Id
private Name id;
private String name;
private int age;
private String sex;
@DnAttribute(value = "uid")
private String uid;
@Attribute(name = "sn")
private String username;
@Attribute(name = "cn")
private String realname;
@Attribute(name = "mail")
private String email;
@Attribute(name = "telephoneNumber")
private String mobile;
@Attribute(name = "title")
private String title;
@Attribute(name = "userPassword")
private String password;
}
package com.ldap;
import com.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.query.LdapQueryBuilder;
import org.springframework.web.bind.annotation.*;
import javax.naming.directory.*;
@RestController
public class Controller {
@Autowired
private LdapTemplate template;
@GetMapping("/getUser")
public void findUser(@RequestParam("uid") String uid) {
User person = template.findOne(LdapQueryBuilder.query().where("uid").is("xutuo"), User.class);
System.out.println(person);
}
@PostMapping("/addUser")
public boolean addUser(@RequestBody 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", vo.getRealname());
attrs.put("sn", vo.getUsername());
attrs.put("displayName", (vo.getRealname()));
attrs.put("mail", vo.getEmail());
attrs.put("telephoneNumber", vo.getMobile());
attrs.put("title", vo.getTitle());
attrs.put("userPassword", vo.getPassword());
template.bind("uid=" + vo.getUsername().trim(), null, attrs);
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
}