我在 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.xml
和 host-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/