Springboot就不用多介紹了吧,相信搜索到這篇文章的人都是Springboot熟手了。
LDAP(Light Directory Access Portocol),它是一款標準的輕量級目錄訪問協議。從其它地方搬來一些它的簡介如下:
所以,LDAP天生是用來查詢的,就像它的名字一樣。LDAP相關概念請自行百度。
Java ldap,Springboot提供了便捷的LDAP開發工具包,引入如下依賴即可:
<!-- LDAP --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-ldap</artifactId></dependency>
然后配置LDAP服務信息:
spring:ldap:urls: ldap://***.***.***.***:389username: cn=<ldapuser>,${spring.ldap.base}password: <ldap_password>base: CN=Users,DC=demo,DC=com
以上配置根據自己的LDAP服務修改。
Springboot提供了LdapTemplate、LdapRepository等封裝工具類用于訪問LDAP服務。首先定義LdapUser對象,用于數據的組裝。
import lombok.Data;
import lombok.ToString;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;import javax.naming.Name;@Data
@ToString
@Entry(objectClasses = {"person"}, base = "CN=Users,DC=demo,DC=com")
public class LdapUser {@Idprivate Name id;@Attribute(name = "cn")private String cn;@Attribute(name = "sn")private String sn;@Attribute(name="mail")private String mail;
}
Spring Boot?objectClasses可以設置多個值,用wireshark抓包查看有"top", "person", "user", "organizationalPerson"等這些類別,也可以在LDAP中自定義類別,查詢時一定要設置正確的類型才能查詢到結果。
自定義訪問接口:
import org.springframework.data.ldap.repository.LdapRepository;public interface LdapUserRepository extends LdapRepository<LdapUser> {
}
定義該接口后,在springboot中即可自動裝載并使用。
無需任何操作,直接裝載LdapTemplate對象即可使用。
兩種方式使用如下:
@SpringBootTest
class AiguardApplicationTests {@Autowiredprivate LdapUserRepository ldapUserRepository;@Autowiredprivate LdapTemplate ldapTemplate;@Testpublic void getAll() {ldapUserRepository.findAll().forEach(System.out::println);List<String> res = ldapTemplate.list("");System.out.println(res.size());}@Testpublic void getOne() {EqualsFilter filter = new EqualsFilter("sAMAccountName", "yaozong.li");LdapQuery query = LdapQueryBuilder.query().where("userPrincipalName").is("yaozong.li@demo.com").or("sAMAccountName").is("yaozong.li");LdapUser person = ldapTemplate.findOne(query, LdapUser.class);System.out.println(person);}@Testpublic void authenticationTest() {boolean success = ldapTemplate.authenticate("", "(sAMAccountName=yaozong.li)", "*********");System.out.println(success);}
}
springboot官網,
2. 查詢人員,如上查詢一個人員信息,該方法分兩步,發起了兩次網絡請求:
?可以看到,最終發送給LDAP服務器的查詢條件是紅框里面的內容,是經過組裝的。詳細查詢語法請自行百度。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态