0

I created a commons library with the intent of injecting headers into the response of every API call. I updated the WebSecurityConfigurerAdaptor and wrote a mockmvc test case to test/assert those headers. However I observed that mockmvc is unable to find/assert those headers in the test even though WebSecurityConfigurerAdaptor injects those headers. Appreciate if you can share your perspective upon any issues you see with this approach.

Below is the WebSecurityConfigurerAdapter snippet:

@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SoaWebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
    @Getter
    @Setter
    private RestTemplateBuilder restTemplateBuilder;


 @Override
    protected void configure(final HttpSecurity http) throws Exception {

        // Disable caching
        http.headers().cacheControl();
        // default deny framing/embedding
        http.headers().frameOptions().deny();

        headerConfigurer(http.headers());

    }

    protected void headerConfigurer(HeadersConfigurer<HttpSecurity> headersConfigurer) {
        log.info("SOACustomWebSecurityConfig: header config invoked");
        headersConfigurer.addHeaderWriter(
                // (HeaderWriter) new StaticHeadersWriter(Arrays.asList(new Header("Access-control-Allow-Origin", "*"),
                // new Header("strict-transport-security", "max-age=31536000; includeSubdomains"))));
                (HeaderWriter) new StaticHeadersWriter("strict-transport-security",
                        "max-age=31536000; includeSubdomains"));
    }

Below is the corresponding test case:

private void testHeadersPresence(String resourceURl, String origin) throws Exception {
        mvc.perform(options(resourceURl).header("Access-Control-Request-Method", "GET").header("Origin", origin))
                .andExpect(header().string("strict-transport-security", "max-age=31536000; includeSubdomains"));
}

The test case fails with the error:

Expected "max-age=31536000; includeSubdomains" but was [null]

Note: the change is being made in a common library (a separate repo) which is included in multiple spring boot services (that offers APIs)

Any insight is much appreciated. Thank you

  • Does this answer your question? [Spring Boot enabling CORS by application.properties](https://stackoverflow.com/questions/42874351/spring-boot-enabling-cors-by-application-properties) – Gannebal Barka Jun 03 '22 at 10:00
  • Thanks for the quick comment. However I think my issue is slightly different. Mockmvc is not able to check the headers in the response that WebSecurityConfigurerAdapter already set. – Vikash Kodati Jun 03 '22 at 10:04

0 Answers0