如何在spring-boot中为ldap安全配置编写测试
身份验证管理器首先验证用户缩写是否存在于ldap中,以及找到的用户是否为为用户筛选器设置的任何组( memberOf any group )。
问:我怎么才能模拟ldap响应呢?例如,我想返回一个不应该在测试范围内进行身份验证的memberOf=CN=Team-INVALID用户。当然,我希望返回一个与userSearchFilter匹配的用户。
但是为了这个测试,我必须模拟哪个类呢?
@Configuration
@Order(1)
@EnableWebSecurity
public class LdapSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchFilter("(&(initials={0})(|" +
"(memberOf=CN=TEAM-1,OU=Intern,DC=my-company)" +
"(memberOf=CN=TEAM-2,OU=Intern,DC=my-company)" +
"))")
.contextSource()
.url(ldapUrl + ldapBase)
.managerDn(ldapUsername)
.managerPassword(ldapPassword);
}
}发布于 2021-06-02 21:18:21
您可以使用LDIF文件为测试定义嵌入式LDAP服务器,如下所示:
spring.ldap.embedded.ldif=classpath:test-server.ldif
spring.ldap.embedded.base-dn=dc=springframework,dc=org
spring.ldap.embedded.port=8389在您的测试中,您可以尝试像在正常流程中一样对该特定用户进行身份验证:
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = {
"spring.ldap.embedded.ldif=classpath:test-server.ldif",
"spring.ldap.embedded.base-dn=${spring.ldap.base}",
"spring.ldap.embedded.port=8389",
"spring.ldap.embedded.url=ldap://localhost:8389/",
"spring.ldap.embedded.credential.username=uid=admin",
"spring.ldap.embedded.credential.password=secret",
"spring.ldap.embedded.validation.enabled=false",
"spring.ldap.urls=ldap://localhost:8389/",
"spring.ldap.username=uid=admin",
"spring.ldap.password=secret"})
public class AuthenticatingLdapApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void loginWithValidUserThenAuthenticated() throws Exception {
FormLoginRequestBuilder login = formLogin()
.user("user")
.password("userpassword");
mockMvc.perform(login)
.andExpect(authenticated().withUsername("user"));
}
@Test
public void loginWithInvalidUserThenUnauthenticated() throws Exception {
FormLoginRequestBuilder login = formLogin()
.user("invalid")
.password("invalidpassword");
mockMvc.perform(login)
.andExpect(unauthenticated());
}
}我在Authenticating with LDAP Guide中找到了这个例子。您可以参考它了解更多详细信息
必需的依赖项:
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>5.1.4</version>
<scope>test</scope>
</dependency>https://stackoverflow.com/questions/67794887
复制相似问题