How to use the right Spring Security configuration during a MockMvc test

rieckpil :

I am trying to test the access of one of my @RestController which is secured by a custom Spring Security configuration. My use case is the following: A HTTP GET to /someEndpoint is secured with authentification, but a HTTP POST request to the same endpoint is not secured. It's working fine when I boot application and test it with my frontend or Postman.

Now I am trying to write tests with MockMvc with the security configuration. I already made it through a lot of answers on StackOverflow, but nothing helped me.

My test setup looks like the following:

@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

}

With this setup all my endpoints are secured and even a HTTP POST is returning a 401 instead of 201. I also enabled the debug log for security and in the debug logs it says that the test uses the default configure(HttpSecurity) and I can't find any of my AntMatchers in the logs:

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

Is it in general possible to use my concrete Spring Security configuration during a MockMvc test or do I have to boot the whole Spring context during the test with @SpringBootTest ? I am using (Spring Boot 2.0.3.RELEASE with Java 1.8)

Thanks in advance!

pDer666 :

With the spring-boot 2.x it is not possible to switch of security with a property anymore. You have to write an own SecurityConfiguration which has to be added to your test context. This security config should allow any request without authentication.

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

test class annotation:

@ContextConfiguration(classes = { ..., TestSecurityConfiguration.class })
public class MyTests {...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94523&siteId=1