如何在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
相关产品推荐
相关产品推荐

