我知道论坛上有很多关于此问题的话题,但仍然没有找到解决方案。
因此,我在vps上的私有JVM / tomcat 8.5.30中部署了两个应用程序。一个是我的ROOT.war,另一个是admin.war,它们可以从http://example.com和http://example.com/admin
访问在我安装ssl证书之前,一切正常。安装它并强制https重定向后,我的admin.war遇到了问题(现在它们都可以从https://example.com和https://example.com/admin访问)
我的管理员使用很多jquery(我无法更改它),每次尝试提交内容时都会收到此错误
Access to XMLHttpRequest at 'http: //example.com/admin/add' from origin 'https: //example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
因此,我正在尝试通过Spring Security解决此问题。在我的安全配置中,
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SiteSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
//.....
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers"));
configuration.addExposedHeader("Access-Control-Allow-Headers");
configuration.setAllowedMethods(Arrays.asList("POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
我同时为我的根应用程序和管理应用程序执行此操作(我不知道对他们两个应用程序这样做是否正确)。仍然不起作用。
有帮助吗?
谢谢!
答案 0 :(得分:1)
如果看到错误
'http://example.com/admin/add' from origin 'https://example.com' has been blocked
有2个问题
1我想您的/add
API调用未重定向到https。理想情况下,应该https://example.com/admin/add
解决此问题
或
2将此setAllowedOrigins
更改为http
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com", "http://example.com"));
configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers"));
configuration.addExposedHeader("Access-Control-Allow-Headers");
configuration.setAllowedMethods(Arrays.asList("POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}