前端使用Axios携带JWT请求时遭遇CORS错误求助
解决SpringBoot后端与Axios前端CORS预检请求鉴权问题
核心问题原因
OPTIONS预检请求本身不会携带Authorization Token,后端的鉴权逻辑如果没有跳过OPTIONS请求,就会触发"找不到用户"的错误,进而导致CORS策略失败。
具体解决方案
1. 让OPTIONS请求跳过鉴权拦截
不管你用的是自定义拦截器还是Spring Security,都需要单独放行OPTIONS方法:
情况1:自定义拦截器(WebMvcConfigurer)
在拦截器的preHandle方法中添加判断:
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 放行OPTIONS预检请求 if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); return true; } // 其他鉴权逻辑... return super.preHandle(request, response, handler); }
情况2:Spring Security配置
在SecurityFilterChain中配置忽略OPTIONS请求的鉴权:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // ...其他配置 .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有OPTIONS请求 .anyRequest().authenticated() ); return http.build(); }
2. 修正CORS配置的错误项
你之前在allowedHeaders里加Access-Control-Allow-Origin是错误的,这个是响应头,不是前端发送的请求头。正确的CORS配置应该包含以下关键项:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("你的前端域名,比如http://localhost:3000") // 不要用*,如果需要带凭证的话 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("Authorization", "Content-Type") // 允许前端发送的请求头 .allowCredentials(true) // 前端带Token/凭证时必须设为true .maxAge(3600); // 预检请求缓存时间,减少OPTIONS请求次数 } }
注意:如果设置
allowCredentials=true,allowedOrigins不能用*,必须指定具体的前端域名。
3. 检查前端Axios配置
确保Axios正确设置了请求头和凭证选项:
// 创建Axios实例 const axiosInstance = axios.create({ baseURL: '你的后端接口地址', withCredentials: true, // 对应后端的allowCredentials headers: { 'Content-Type': 'application/json' } }); // 请求拦截器添加Token axiosInstance.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); });
内容的提问来源于stack exchange,提问作者Wolf Ganger
相关产品推荐
相关产品推荐

