CORS预检错误:Postman可正常调用但Spring Security认证时失败
解决CORS预检错误及Spring Security认证问题
问题根源
- 预检请求被拦截:CORS预检请求使用
OPTIONS方法,当前Spring Security配置未允许该方法跳过认证校验,直接被拦截。 - 路径匹配范围不足:配置中
requestMatchers("/account")仅匹配/account根路径,但实际请求的是/account/{username},导致目标路径未被放行,触发认证拦截。 - CORS凭证传递未开启:前端携带
Authorization头发起请求,但CORS配置未明确允许凭证传递。
修复步骤
1. 调整Spring Security配置,放行预检请求与目标路径
更新SecurityConfig,确保OPTIONS请求无需认证,同时匹配所有/account下的子路径:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity .csrf(AbstractHttpConfigurer::disable) // 复用WebMvc的CORS配置 .cors(Customizer.withDefaults()) .exceptionHandling(exception -> exception .authenticationEntryPoint( (req, res, ex) -> { res.sendError( HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage() ); } ) ) .authorizeHttpRequests(auth -> auth // 放行所有OPTIONS预检请求 .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行account下所有子路径 .requestMatchers("/account/**").permitAll() .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()); return httpSecurity.build(); } }
2. 完善CORS配置,允许凭证传递
更新WebConfig,添加凭证允许配置,同时补全OPTIONS方法的授权:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry .addMapping("/**") .allowedOrigins("http://localhost:5500") .allowedMethods("GET", "POST", "OPTIONS") .allowedHeaders("Content-Type", "Authorization", "Accept") .allowCredentials(true); } }
3. 前端Fetch补充凭证传递配置
在fetch请求中添加credentials: 'include',确保Authorization头正确传递到后端:
const callApi = () => { fetch(url, { method: method, headers: headers, credentials: 'include' }).then(res => { res.json().then(data => console.log(data)); }).catch(err => console.error('请求错误:', err)); }
验证要点
- 重启后端服务后,再次调用接口,检查浏览器控制台是否仍有CORS错误。
- 用Postman测试认证后的接口,确认能正常返回用户信息。
内容的提问来源于stack exchange,提问作者yoo
相关产品推荐
相关产品推荐

