【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource (Spring)请求的资源上不存在“Access-Control-Allow-Origin”标头(Spring)
【发布时间】:2026-01-09 08:45:02
【问题描述】:

我知道论坛上有很多关于这个问题的帖子,但仍然没有找到解决方案。

所以,我在我的 vps 上的私有 JVM/tomcat 8.5.30 中部署了两个应用程序。一个是我的 ROOT.war,另一个是 admin.war 他们可以从 http://example.comhttp://example.com/admin 访问

在我安装 ssl 证书之前,一切正常。安装它并强制 https 重定向后,我的 admin.war 出现问题(现在它们都可以从 https://example.comhttps://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;
    }
}

我为我的根应用程序和我的管理应用程序都这样做(我不知道对它们都这样做是否正确)。还是不行。

有什么帮助吗?

谢谢!!

【问题讨论】:

    标签: spring spring-security cors


    【解决方案1】:

    如果你看到错误

    'http://example.com/admin/add' from origin 'https://example.com' has been blocked
    

    有两个问题

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

    【讨论】:

      最近更新 更多