java - Tomcat 启用 CORS : POST request from Safari returns 200, Chrome 和 Firefox 返回 403

标签 java google-chrome tomcat cors catalina

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

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

经过一些研究,我发现我必须添加 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 响应。

最佳答案

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

} 

关于java - Tomcat 启用 CORS : POST request from Safari returns 200, Chrome 和 Firefox 返回 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116173/

相关文章:

javascript - 从 chrome 扩展程序传递大 blob 或文件

java - eclipse 上的 Apache tomcat 故障排除

java - 使用 XOM 在具有默认命名空间的 xml 上应用 xpath

java - 为什么 HttpURLConnection 不发送 HTTP 请求

java - 使用 Citrus 时如何禁用服务器证书中的主机名验证

javascript - 如何限制图片上传的大小?如果超过限制大小则显示消息?

javascript - jquery innerWidth/outerWidth 和 javascript clientWidth/offsetWidth 在 chrome 上给出了错误的值

java - tomcat 8.0.32 - 生产服务器中 Server.xml 配置中的性能调整

java - JSP/Servlet 重写 URL

java - 如何查找值为 X 的节点的父节点