Spring Boot+Spring Security+Vue.js+Axios遇认证与CORS错误求助
问题排查与解决方案
核心问题分析
你的问题同时涉及CORS配置冲突、前端代理无效、Axios请求格式错误以及Spring Security权限拦截四个方面,以下是具体排查和修复步骤:
1. 后端Spring Security配置修正
问题点
- 同时使用
WebMvcConfigurer的addCorsMappings和Spring Security的CORS配置,导致规则冲突 allowedOrigins设为*但开启了allowCredentials,违反浏览器安全规则(带凭证的请求不允许通配符Origin)- 未放行OPTIONS预检请求,导致Spring Security拦截预检请求返回401/403
修改后代码
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class WebSecurityConfig { @Bean public UserDetailsService userDetailsService(BCryptPasswordEncoder bCryptPasswordEncoder) { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withUsername("user") .password(bCryptPasswordEncoder.encode("userPass")) .roles("USER") .build()); manager.createUser(User.withUsername("admin") .password(bCryptPasswordEncoder.encode("adminPass")) .roles("USER", "ADMIN") .build()); return manager; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { final CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type")); // 替换为你的前端实际地址(如Vite默认的http://localhost:5173) corsConfiguration.setAllowedOrigins(List.of("http://localhost:5173")); corsConfiguration.setAllowedMethods(List.of("GET", "POST", "OPTIONS", "PUT", "DELETE")); corsConfiguration.setAllowCredentials(true); corsConfiguration.setExposedHeaders(List.of("Authorization")); http.csrf() .disable() .cors().configurationSource(r -> corsConfiguration) .and() .authorizeRequests() // 放行OPTIONS预检请求 .antMatchers(HttpMethod.OPTIONS).permitAll() .antMatchers(HttpMethod.DELETE) .hasRole("ADMIN") .antMatchers("/api/**") .hasAnyRole("ADMIN") .antMatchers("/user/**") .anonymous() .anyRequest() .authenticated() .and() .httpBasic() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); return http.build(); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } // 移除WebMvcConfigurer的addCorsMappings方法,避免和Security的CORS配置冲突 }
2. 前端Vite代理配置修正
问题点
- 使用了Vue CLI的
devServer配置,但项目基于Vite,代理规则完全无效 - 代理路径匹配过于具体,应该匹配整个
/api前缀而非单个接口
修改后vite.config.js代码
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], server: { proxy: { '/api': { target: 'http://localhost:9050/', changeOrigin: true, withCredentials: true } } } })
3. Axios请求代码修正
问题点
- 直接请求后端完整地址,未使用代理路径,导致跨域
- Authorization头格式错误(Basic认证需要base64编码用户名密码)
- 错误添加了后端才需要返回的
Access-Control-*响应头 withCredentials放在了headers里,应该在配置根节点
修改后代码
// 计算admin:adminPass的base64编码 const authToken = btoa('admin:adminPass'); const {data, status} = await axios.get<GetProductPojoResponse>( '/api/v1/products/all', // 使用代理路径,无需写完整后端地址 { withCredentials: true, // 移到配置根节点 headers: { Accept: 'application/json', Authorization: `Basic ${authToken}` // 正确的Basic认证格式 // 移除所有Access-Control-*请求头,这些是后端返回的字段 }, }, ); console.log(JSON.stringify(data, null, 4)); console.log('response status is: ', status); return data;
总结问题根源
- 后端CORS配置违反浏览器安全规则(通配符Origin+允许凭证),触发CORS错误
- 前端代理配置格式错误(用了Vue CLI的配置而非Vite),导致跨域请求未被代理
- Axios请求的Basic认证格式错误,且未使用代理路径,加剧认证失败和跨域问题
- 未放行OPTIONS预检请求,导致Spring Security拦截预检请求返回401/403
内容的提问来源于stack exchange,提问作者Tony B
相关产品推荐
相关产品推荐

