Spring Boot v2.5.2集成Spring Security时Vue调用接口报CORS跨域错误
问题根因
你遇到的跨域报错本质是请求先被Spring Security拦截未通过认证,直接返回了无CORS响应头的错误响应,同时存在CORS地址匹配冲突问题,按照以下步骤修改即可修复:
修复步骤
- 修正Controller上
@CrossOrigin注解的地址配置,删掉末尾多余的斜杠,和Security配置的地址保持一致:
// 原错误写法:@CrossOrigin(origins = "http://localhost:8081/") @CrossOrigin(origins = "http://localhost:8081") @RestController @RequestMapping("/api") public class IndexController { // 原有接口逻辑保持不变 }
- 更新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; } }
- 调试阶段可选优化:如果你暂时不需要Spring Security的认证能力,可以直接在
application.properties中添加配置关闭安全自动配置,快速验证接口连通性:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
内容的提问来源于stack exchange,提问作者Zabon
相关产品推荐
相关产品推荐

