Spring Boot教程(四十二)LDAP來管理用戶信息(2)


  • 使用spring-data-ldap的基礎用法,定義LDAP中屬性與我們Java中定義實體的關系映射以及對應的Repository
    @Data
    @Entry(base = "ou=people,dc=didispace,dc=com", objectClasses = "inetOrgPerson")
    public class Person {
    
        @Id
        private Name id;
        @DnAttribute(value = "uid", index = 3)
        private String uid;
        @Attribute(name = "cn")
        private String commonName;
        @Attribute(name = "sn")
        private String suerName;
        private String userPassword;
    
    }
    
    public interface PersonRepository extends CrudRepository<Person, Name> {
    
    }
    

      

    通過上面的定義之后,已經將Person對象與LDAP存儲內容實現了映射,我們只需要使用PersonRepository就可以輕松的對LDAP內容實現讀寫。

  • 創建單元測試用例讀取所有用戶信息:
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class ApplicationTests {
    
    	@Autowired
    	private PersonRepository personRepository;
    
    	@Test
    	public void findAll() throws Exception {
    		personRepository.findAll().forEach(p -> {
    			System.out.println(p);
    		});
    	}
    }
    

      

    啟動該測試用例之后,我們可以看到控制台中輸出了剛才維護在ldap-server.ldif中的用戶信息:

    2018-01-27 14:25:06.283  WARN 73630 --- [           main] o.s.ldap.odm.core.impl.ObjectMetaData    : The Entry class Person should be declared final
    Person(id=uid=ben,ou=people,dc=didispace,dc=com, uid=ben, commonName=didi, suerName=zhaiyongchao, userPassword=123,83,72,65,125,110,70,67,101,98,87,106,120,102,97,76,98,72,72,71,49,81,107,53,85,85,52,116,114,98,118,81,61)
    

      

    添加用戶

    通過上面的入門示例,如果您能夠獨立完成,那么在Spring Boot中操作LDAP的基礎目標已經完成了。

    如果您足夠了解Spring Data,其實不難想到,這個在其下的子項目必然也遵守Repsitory的抽象。所以,我們可以使用上面定義的PersonRepository來輕松實現操作,比如下面的代碼就可以方便的往LDAP中添加用戶:

    Person person = new Person();
    person.setUid("uid:1");
    person.setSuerName("AAA");
    person.setCommonName("aaa");
    person.setUserPassword("123456");
    personRepository.save(person);
    

      

    如果還想實現更多操作,您可以參考spring-data-ldap的文檔來進行使用。

    連接LDAP服務端

    在本文的例子中都采用了嵌入式的LDAP服務器,事實上這種方式也僅限於我們本地測試開發使用,真實環境下LDAP服務端必然是獨立部署的。

    在Spring Boot的封裝下,我們只需要配置下面這些參數就能將上面的例子連接到遠端的LDAP而不是嵌入式的LDAP。

    spring.ldap.urls=ldap://localhost:1235
    spring.ldap.base=dc=didispace,dc=com
    spring.ldap.username=didispace
    spring.ldap.password=123456
    

      

    源碼來源


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM