如何在 MockMvc 测试期间使用正确的 Spring Security 配置

rie*_*pil 3 java spring spring-mvc spring-security spring-boot

我正在尝试测试@RestController由自定义 Spring Security 配置保护的其中一个的访问权限。我的使用情况是如下:a HTTPGET/someEndpoint固定与认证,但HTTPPOST请求到同一个端点是不安全的。当我启动应用程序并使用我的前端或 Postman 对其进行测试时,它工作正常。

现在我正在尝试MockMvc使用安全配置编写测试。我已经在 StackOverflow 上通过了很多答案,但没有任何帮助。

我的测试设置如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = MyController.class)
@WebAppConfiguration
@ContextConfiguration
public class AssessmentControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void init() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .alwaysDo(print())
                .apply(SecurityMockMvcConfigurers.springSecurity())
                .build();
    }

    // some test methods

}
Run Code Online (Sandbox Code Playgroud)

有了这个设置,我所有的端点都得到了保护,甚至 HTTPPOST也返回了一个401而不是201. 为了安全起见,我还启用了调试日志,在调试日志中,它说测试使用了default configure(HttpSecurity)并且我在日志中找不到任何 AntMatchers:

2018-07-04 19:20:02.829 DEBUG 2237 --- [           main] s.s.c.a.w.c.WebSecurityConfigurerAdapter : Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).
2018-07-04 19:20:03.097 DEBUG 2237 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'authenticated', for org.springframework.security.web.util.matcher.AnyRequestMatcher@1
2018-07-04 19:20:03.127 DEBUG 2237 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes
2018-07-04 19:20:03.130 DEBUG 2237 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes
2018-07-04 19:20:03.161  INFO 2237 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5a75ec37, org.springframework.security.web.context.SecurityContextPersistenceFilter@3f736a16, org.springframework.security.web.header.HeaderWriterFilter@529c2a9a, org.springframework.security.web.csrf.CsrfFilter@7f93dd4e, org.springframework.security.web.authentication.logout.LogoutFilter@707b1a44, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@26c89563, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@1e0a864d, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@22ebccb9, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@53abfc07, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4aa21f9d, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2c05ff9d, org.springframework.security.web.session.SessionManagementFilter@26bbe604, org.springframework.security.web.access.ExceptionTranslationFilter@4375b013, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@a96d56c]
2018-07-04 19:20:03.236  INFO 2237 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2018-07-04 19:20:03.237  INFO 2237 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
Run Code Online (Sandbox Code Playgroud)

通常是否可以在MockMvc测试期间使用我的具体 Spring Security 配置,或者我是否必须在测试期间使用启动整个 Spring 上下文@SpringBootTest?我正在使用(Spring Boot 2.0.3.RELEASE with Java 1.8)

提前致谢!

pDe*_*666 5

使用 spring-boot 2.x 时,无法再使用属性切换安全性。您必须编写一个自己的 SecurityConfiguration,它必须添加到您的测试上下文中。此安全配置应允许任何未经身份验证的请求。

@Configuration
@EnableWebSecurity
public class TestSecurityConfiguration extends WebSecurityConfigurerAdapter{
   @Override
   protected void configure(HttpSecurity http) throws Exception {
   http.csrf().disable().authorizeRequests().anyRequest().permitAll();
   }

   @Override
   public void configure(WebSecurity web) throws Exception{
     web.debug(true);
   }
}
Run Code Online (Sandbox Code Playgroud)

测试类注释:

@ContextConfiguration(classes = { ..., TestSecurityConfiguration.class })
public class MyTests {...
Run Code Online (Sandbox Code Playgroud)