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

Spring Boot v2.5.2集成Spring Security时Vue调用接口报CORS跨域错误

问题根因

你遇到的跨域报错本质是请求先被Spring Security拦截未通过认证,直接返回了无CORS响应头的错误响应,同时存在CORS地址匹配冲突问题,按照以下步骤修改即可修复:


修复步骤

  1. 修正Controller上@CrossOrigin注解的地址配置,删掉末尾多余的斜杠,和Security配置的地址保持一致:
// 原错误写法:@CrossOrigin(origins = "http://localhost:8081/")
@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class IndexController {
    // 原有接口逻辑保持不变
}
  1. 更新SecurityConfig配置,补充预检请求放行规则、禁用CSRF,确保跨域请求可以正常通过安全校验:
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
            .and()
            // 前后端分离场景无需CSRF校验,直接禁用
            .csrf().disable()
            .authorizeRequests()
                // 放行所有OPTIONS预检请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 放行业务接口
                .antMatchers("/api/**").permitAll()
                .anyRequest().authenticated();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8081"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
  1. 调试阶段可选优化:如果你暂时不需要Spring Security的认证能力,可以直接在application.properties中添加配置关闭安全自动配置,快速验证接口连通性:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 07:48:03