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

Spring5+Angular6登录配置遇OPTIONS预检401错误及解决方法

解决Spring 5 + Angular登录时的CORS OPTIONS预检401错误

我明白你在Spring 5项目对接Angular登录功能时,碰到了CORS预检请求(OPTIONS)返回401的棘手问题——这是因为Spring Security默认会拦截OPTIONS请求并要求认证,但浏览器发送的预检请求并不会携带认证信息,自然就触发了权限错误。下面是通过调整Spring Security执行顺序和CORS配置来解决问题的具体方案:

核心修复方案

1. 调整Security配置的执行优先级

给你的WebSecurityConfiguration类添加@Order(4)注解,确保它在其他可能的CORS或Security配置之前执行,避免被后续配置覆盖规则:

@Order(4)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    // 后续配置内容
}

2. 豁免OPTIONS请求的认证校验

在configure(HttpSecurity http)方法中,明确声明所有OPTIONS请求无需经过认证拦截,同时启用Spring的CORS支持:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有OPTIONS预检请求
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/**").hasAnyRole("ADMIN","USER")
            .anyRequest().authenticated()
        .and()
            .httpBasic()
        .and()
            .cors(); // 启用全局CORS配置
}

3. 配置全局跨域规则

添加CorsConfigurationSource Bean,设置允许跨域的基础规则(你可以根据实际业务需求调整限制范围,这里使用默认的宽松配置):

@Bean
CorsConfigurationSource corsConfigurationSource() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

方案原理说明

  • @Order(4)确保当前Security配置的优先级足够高,不会被其他同类配置覆盖核心规则;
  • 显式放行OPTIONS请求,避免Spring Security对浏览器的预检请求做认证校验,这是解决401错误的关键;
  • 启用cors()并配置全局规则,让Spring正确处理跨域请求的响应头,符合浏览器的CORS校验要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:50:38