[JAVA] Spring Framework 5.2.0 --Vary header duplication due to CORS handling change

When using Spring Security with 5.2.0.RELEASE, the following Vary response headers may be duplicated.

Especially when executing the test of @CrossOrigin Controller like this, it will be duplicated.

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(context)
                .apply(SecurityMockMvcConfigurers.springSecurity()).build();
    }

Target

Spring Framework 5.2.0.RELEASE (spring-web) + Use Spring Security

Cause

Occurs when both the Spring Security CORS setting and the @ CrossOrigin annotation are set for the endpoint. This is because the handleInternal method of DefaultCorsProcessor.java has been changed to add the Vary header with the processRequest method. The CORS in Spring Security and the CORS Filter in WebMVC seem to be covered and may be executed twice.

DefaultCorsProcessor.java


public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    response.addHeader(HttpHeaders.VARY, HttpHeaders.ORIGIN);
    response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
    response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
    ...

Click here for differences

Workaround

Stop the cors setting that is set as follows in Spring Security config.

SpringSecurityConfig.java


@Override
public void configure(HttpSecurity http) throws Exception {
    http...
        .cors()
            .configurationSource(this.corsConfigurationSource());
}

private CorsConfigurationSource corsConfigurationSource() {
    ...
}

Until now, it was okay to run CorsFilter twice, but since the location of the header addition has changed, it has become duplicated after running twice.

You shouldn't set CORS for Spring Security and @CrossOrigin. .. If there is any other good solution. .. .. .. ..

By the way, there are quite a few other changes. 5.2.0 scary https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-5.x

Recommended Posts

Spring Framework 5.2.0 --Vary header duplication due to CORS handling change
Major changes related to Spring Framework 5.0 Test