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

ryoqjall  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(354)

我如何为一个项目编写测试 ldap 中的安全配置 spring-boot ?
身份验证管理器首先验证ldap中是否存在用户首字母缩写,以及找到的用户是否为 memberOf 为用户筛选器设置的任何组。
问题:我怎么能模拟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);
    }
}
6yjfywim

6yjfywim1#

您可以使用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());
    }
}

我在ldap认证指南中找到了这个示例。你可以参考它了解更多细节
所需依赖项:

<dependency>
    <groupId>com.unboundid</groupId>
    <artifactId>unboundid-ldapsdk</artifactId>
    <version>5.1.4</version>
    <scope>test</scope>
</dependency>

相关问题