Tomcat enable CORS: POST request from Safari returns 200, Chrome and Firefox return 403

I have backend running on Tomcat 8.5, Java Spring on Amazon EC2 instance.

I make a POST request from my React app. The requests from Chrome and Firefox return 403, while the request from Safari returns 200 and the expected data.

After some research I found out that I must add this code somewhere to enable CORS. I am not familiar with Tomcat and don’t know where exactly to put this piece of code.

I have the following web.xml files listed from running the find command:

./webapps/host-manager/WEB-INF/web.xml
./webapps/ROOT/WEB-INF/web.xml
./webapps/docs/appdev/sample/web/WEB-INF/web.xml
./webapps/docs/WEB-INF/web.xml
./webapps/examples/WEB-INF/web.xml
./webapps/manager/WEB-INF/web.xml
./conf/web.xml

I tried to add the code in host-manager/WEB-INF/web.xml and host-manager/WEB-INF/web.xml at the same time and tried to run it, but still get a 403 response.

Answer

Try adding the following code to your Spring application. It handles CORS configuration for the entire application.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
            .and()
            .headers().disable()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

} 

Leave a Reply

Your email address will not be published. Required fields are marked *