Tomcat 启用 CORS:来自 Safari 的 POST 请求返回 200,Chrome 和 Firefox 返回



我在Tomcat 8.5上运行后端,在Amazon EC2实例上运行Java Spring。

我从我的 React 应用程序发出 POST 请求。来自Chrome和Firefox的请求返回403,而来自Safari的请求返回200和预期数据。

经过一些研究,我发现我必须在某处添加此代码才能启用 CORS。我不熟悉Tomcat,也不知道把这段代码放在哪里。

我在运行 find 命令时列出了以下 web.xml 个文件:

./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

我尝试同时在 host-manager/WEB-INF/web.xmlhost-manager/WEB-INF/web.xml 中添加代码并尝试运行它,但仍然得到 403 响应。

尝试将以下代码添加到您的 Spring 应用程序中。它处理整个应用程序的 CORS 配置。

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

尽管这个答案告诉你如何使用 Spring 来处理它,但它并没有回答你原来的问题。

您需要将 CORS 筛选器添加到您的案例中./conf/web.xml。来自 Tomcat 文档:

Tomcat提供了许多过滤器,可以配置为使用所有使用 $CATALINA_BASE/conf/web.xml 的 Web 应用程序,或者可能是通过在应用程序的 WEB-INF/web.xml。

最新更新