基于EmbeddedLdapRule构建类AD服务器验证用户LDAP查询的技术问询
没问题,我帮你梳理一下如何给EmbeddedLdapRule添加AD风格的user类,并完成查询验证的完整流程:
解决方案:为EmbeddedLdapRule添加
user类并验证LDAP查询 1. 补全schema.ldif中的user类定义
你提供的schema片段不完整,需要补充符合AD规范的user结构类属性。下面是完整的LDIF内容,定义了标准AD风格的user类:
dn: cn=user,cn=schema,cn=configuration,dc=example,dc=com changetype: add objectClass: top objectClass: classSchema cn: user ldapDisplayName: user objectClassCategory: 3 # 标记为结构类 governsID: 1.2.840.113556.1.5.1 # AD默认user类的OID rDNAttID: cn subClassOf: top mayContain: cn, sn, givenName, displayName, userPrincipalName, sAMAccountName, userPassword
说明:这里的OID和可包含属性完全参考AD原生
user类配置,你可以根据测试需求调整mayContain里的属性列表。
2. 调整测试代码的规则配置
你的测试代码需要补全build()方法,同时建议指定基础DN来和schema配置对齐,确保服务器正常启动:
import org.zapodot.junit.ldap.EmbeddedLdapRule import org.zapodot.junit.ldap.EmbeddedLdapRuleBuilder import org.junit.Rule import spock.lang.Specification class FooSpec extends Specification { @Rule public EmbeddedLdapRule embeddedLdapRule = EmbeddedLdapRuleBuilder .newInstance() .withBaseDn("dc=example,dc=com") // 和schema、导入数据的DN保持一致 .withSchema('schema.ldif') // 加载自定义user类的schema .importingLdifs('import.ldif') // 导入测试用的user实体 .build() // 必须调用build()完成规则构建 def "verify user entity query works"() { given: "Established LDAP context" def ldapContext = embeddedLdapRule.context() when: "Search for all user objects" def searchControls = new javax.naming.directory.SearchControls() searchControls.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE) def searchResults = ldapContext.search("dc=example,dc=com", "(objectClass=user)", searchControls) then: "Test user is found with correct attributes" searchResults.hasMoreElements() def testUser = searchResults.nextElement() testUser.attributes.get("cn").get() == "testUser" testUser.attributes.get("sAMAccountName").get() == "johnt" } }
3. 编写import.ldif添加测试用户
创建import.ldif文件,添加一个符合自定义user类的测试实体,用于验证查询:
dn: cn=testUser,dc=example,dc=com changetype: add objectClass: top objectClass: user cn: testUser sn: Test givenName: John displayName: John Test userPrincipalName: john.test@example.com sAMAccountName: johnt userPassword: P@ssw0rd
4. 运行测试验证
启动Spock测试后,EmbeddedLdapRule会自动完成以下操作:
- 启动嵌入式LDAP服务器
- 加载你定义的
user类schema - 导入测试用户数据
- 提供LDAP上下文供你执行查询验证
内容的提问来源于stack exchange,提问作者pointyhat
相关产品推荐
相关产品推荐

