Spring Security HttpSecurity配置测试

JJ *_*kar 17 testing spring spring-security

我有一个Spring Boot + Spring Security应用程序,它有几个antMatchers路径; 一些fullyAuthenticated(),一些permitAll().

如何编写一个测试验证SecurityConfiguration我的端点/api/**(以及最终其他)是否正确安全?

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {
        http
            //...
            .antMatchers("/api/**").fullyAuthenticated()
    }

}
Run Code Online (Sandbox Code Playgroud)

使用spring-boot-1.5.2.RELEASE,spring-security-core-4.2.2-release.

澄清1:我希望尽可能直接测试SecurityConfiguration,而不是通过其中一个/api/**端点进行传递测试,这些端点可能有自己的@PreAuthorize安全性.

澄清2:我想要类似于这个WebSecurityConfigurerAdapterTests的东西.

澄清3:@Autowire理想情况下HttpSecurity,我想在Spring Security层进行测试.

Kla*_*aek 7

所以你想确保如果有人改变了,.antMatchers("/api/**")那么.antMatchers("/WRONG_PATH/**")你有一个测试可以解决这个问题?

您定义使用的规则HttpSecurity最终将配置一个FilterChainProxy或多个SecurityFilterChain,每个规则都有一个过滤器列表。每个过滤器,例如UsernamePasswordAuthenticationFilter (用于基于表单的登录),都将RequestMatcher在超类中定义AbstractAuthenticationProcessingFilter。问题是RequestMatcher是一个接口,目前有 12 个不同的实现,其中包括AndRequestMatcherOrRequestMatcher,因此匹配逻辑并不总是简单。最重要的RequestMatcher是只有一种方法boolean matches(HttpServletRequest request),并且实现通常不会公开配置,因此您必须使用反射来访问每个RequestMatcher实现的私有配置(将来可能会改变)。

如果您沿着这条路径走下去,自动装配FilterChainProxy到测试中并使用反射对配置进行逆向工程,则必须考虑您拥有的所有实现依赖项。例如,WebSecurityConfigurerAdapter有一个默认的过滤器列表,它可能会在版本之间发生变化,除非禁用它,并且当它被禁用时,您必须显式定义每个过滤器。此外,新的过滤器RequestMatchers可能会随着时间的推移而添加,或者在一个版本的 Spring Security 中生成的过滤器链HttpSecurity可能在下一版本中略有不同(也许不太可能,但仍然有可能)。

为 Spring Security 配置编写通用测试在技术上是可行的,但这并不是一件容易的事情,而且 Spring Security 过滤器当然不是为了支持这一点而设计的。自 2010 年以来,我一直在广泛使用 Spring Security,而且我从未需要过这样的测试,而且我个人认为尝试实现它是浪费时间。我认为最好把时间花在编写一个测试框架上,这样可以轻松编写集成测试,这将隐式测试安全层和业务逻辑。