HarshvardhanSharma
HarshvardhanSharma

Reputation: 786

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.

Upvotes: 0

Views: 357

Answers (2)

Josh Correia
Josh Correia

Reputation: 4346

Even though this answer tells you how to handle it with Spring, it doesn't answer your original question.

You need to add the CORS Filter to ./conf/web.xml in your case. From the Tomcat documentation:

Tomcat provides a number of Filters which may be configured for use with all web applications using $CATALINA_BASE/conf/web.xml or may be configured for individual web applications by configuring them in the application's WEB-INF/web.xml.

Upvotes: 0

Kushagra Goyal
Kushagra Goyal

Reputation: 272

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

} 

Upvotes: 1

Related Questions