【问题标题】:Tomcat enable CORS: POST request from Safari returns 200, Chrome and Firefox return 403Tomcat 启用 CORS:来自 Safari 的 POST 请求返回 200,Chrome 和 Firefox 返回 403
【发布时间】:2019-06-04 14:01:30
【问题描述】:

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

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

经过一番研究,我发现我必须在 somewhere 添加 this 代码才能启用 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响应。

【问题讨论】:

    标签: java google-chrome tomcat cors catalina


    【解决方案1】:

    尝试将以下代码添加到您的 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);
        }
    
    } 
    

    【讨论】:

    • Kushagra,我是一名前端开发人员,需要知道在哪里添加这个。
    • 您可以在源目录中的任何位置添加此类。例如src/main/java/application/security。如果您使用的是 maven,请记住将 org.springframework.boot:spring-boot-starter-security 库添加到您的 build.gradle 或相应的库到 pom.xml
    【解决方案2】:

    尽管this answer 告诉您如何使用 Spring 处理它,但它并没有回答您最初的问题。

    您需要在您的情况下将CORS Filter 添加到./conf/web.xml。来自 Tomcat 文档:

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

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多