如何在 spring 中测试 LDAP 安全配置?

How to test LDAP security configuration in spring?

如何为 spring-boot 中的 ldap 安全配置编写测试?

身份验证管理器首先验证用户首字母是否存在于 ldap 中,并且找到的用户是 memberOf 为用户过滤器设置的任何组。

问题:我怎样才能完全模拟 ldap 响应?例如,我想 return 一个 memberOf=CN=Team-INVALID 的用户不应该在测试范围内进行身份验证。 当然,我想 return 匹配 userSearchFilter 的用户。

但是我必须为这个测试模拟哪个 class?

@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);
    }
}

您可以为测试定义带有 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>