You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成Spring Security时CORS配置失效问题的解决求助

解决Spring Boot + Spring Security的CORS跨域问题

我看了你贴的代码,问题出在Spring Security的CORS配置没有正确生效——你虽然创建了CorsConfiguration对象,但并没有把它集成到Security的过滤链中。而Spring Security的过滤器优先级比Spring MVC的CORS处理要高,所以之前的@CrossOrigin或者单独的WebConfig都会被Security拦截掉,自然起不到作用。

下面是具体的修复步骤:

1. 配置CORS规则源

首先创建一个CorsConfigurationSource的Bean,把你的跨域规则统一注册进去,这样Spring Security就能识别并应用这些规则:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    // 生产环境请替换为具体的前端域名,不要用*(如果开启了allowCredentials)
    configuration.setAllowedOrigins(List.of("http://localhost:3000")); 
    configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
    configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
    // 如果前端需要携带cookie或认证信息,开启这个
    configuration.setAllowCredentials(true);
    configuration.setExposedHeaders(List.of("Authorization"));
    
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 对所有路径应用跨域规则
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

2. 在Spring Security中启用CORS

修改你的configure(HttpSecurity http)方法,添加.cors().configurationSource(corsConfigurationSource()),让Security明确使用上面的跨域配置:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            // 启用CORS并绑定配置源
            .cors().configurationSource(corsConfigurationSource())
            .and()
            .authorizeRequests()
            // 注意:你的路径之前少了开头的斜杠,这会导致匹配失败!
            .antMatchers("/helloadmin").hasRole("ADMIN")
            .antMatchers("/hellouser").hasAnyRole("USER","ADMIN")
            .antMatchers("/techshop/web/v1/product/save").hasRole("ADMIN")
            .antMatchers("/techshop/web/v1/product").hasAnyRole("USER", "ADMIN")
            .antMatchers("/techshop/web/v1/product/{id}").hasRole("ADMIN")
            .antMatchers("/authenticate").permitAll()
            .anyRequest().authenticated()
            .and().exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.addFilterBefore(customJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

3. 修正前端请求的URL

你的前端请求地址写错了!localhost:8080/test应该对应后端的/authenticate接口,而且必须带上协议(http/https),否则浏览器会识别为相对路径:

let datos = { username:"admin", password:"admin" }
const getToken = () => {
    axios({
        method: 'post',
        url: 'http://localhost:8080/authenticate', // 修正URL
        data: datos,
        withCredentials: true // 如果开启了allowCredentials,需要加上这个
    });
}
getToken()

关键注意点

  • 生产环境不要用*作为allowedOrigins:如果allowCredentials设为true,浏览器不允许*作为允许的源,必须指定具体的域名(比如http://your-frontend-domain.com)。
  • 预检请求(OPTIONS)的处理:Spring Security会自动处理OPTIONS类型的预检请求,只要你正确配置了CORS,就不会被拦截。
  • 路径匹配的斜杠:之前你的antMatchers里的路径少了开头的/,会导致路径匹配失败,这也可能间接导致跨域请求被拒绝。

这样修改后,你的CORS问题应该就能解决了。

内容的提问来源于stack exchange,提问作者Miguel Valbuena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 10:12:32