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

如何在Spring WebFlux Security中绕过OPTIONS请求的认证校验?

问题根因

你配置的pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()属于Spring Security授权阶段的判定规则,执行顺序晚于自定义认证过滤器。而你自定义的AuthenticationWebFilter的RequiresAuthenticationMatcher仅排除了/api/demo路径,没有覆盖OPTIONS请求,所以OPTIONS请求会先进入认证过滤器触发customAuthenticationManager逻辑,之后才会走到授权放行的步骤,不符合你的预期。

解决方法

修改自定义认证过滤器的匹配规则,将所有OPTIONS请求也加入免认证白名单即可,修改后的authenticationWebFilter代码如下:

/**
 * Method to get the instance of {@link AuthenticationWebFilter}.
 *
 * @return {@link AuthenticationWebFilter} instance.
 */
private AuthenticationWebFilter authenticationWebFilter() {
    AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(
        customAuthenticationManager);
    authenticationWebFilter.setServerAuthenticationConverter(customAutenticationConverter);
    // 组合白名单规则:/api/demo路径 + 所有OPTIONS请求
    ServerWebExchangeMatcher whiteList = ServerWebExchangeMatchers.matchers(
        ServerWebExchangeMatchers.pathMatchers("/api/demo"),
        ServerWebExchangeMatchers.pathMatchers(HttpMethod.OPTIONS, "/**")
    );
    NegatedServerWebExchangeMatcher negateWhiteList = new NegatedServerWebExchangeMatcher(whiteList);
    authenticationWebFilter.setRequiresAuthenticationMatcher(negateWhiteList);
    return authenticationWebFilter;
}

修改后,OPTIONS请求会被匹配到免认证规则,直接跳过自定义认证过滤器,不会触发customAuthenticationManager的逻辑,后续走到授权阶段也会匹配你预先配置的permitAll规则正常放行。

补充优化:你当前的CORS配置仅允许OPTIONS方法跨域,如果业务需要支持GET/POST/PUT等其他请求方法跨域,可以将corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS)修改为corsConfiguration.addAllowedMethod("*")放行所有请求方法。

内容的提问来源于stack exchange,提问作者Rohit Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:18:04