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

迁移至Spring Security 6后未认证用户访问抛出AuthenticationException问题

Spring Boot 3/Spring Security 6 未认证用户行为异常问题解决

结论

这不是Spring Security 6的默认正常行为,你的WebSecurityConfig需要调整。Spring Security 6仍支持匿名认证,但配置oauth2ResourceServer().jwt()后,默认匿名处理逻辑被覆盖,导致未认证请求直接抛出AuthenticationException,而非进入匿名状态。

调整方案

显式启用匿名认证,并优化请求匹配规则的配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    log.debug("Configuring HTTP Security");
    http
        .csrf().disable()
        .cors()
        .and()
        .headers()
        .frameOptions().disable()
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .exceptionHandling()
        .and()
        // 显式开启匿名认证
        .anonymous()
        .and()
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/sf/**").permitAll()
            .requestMatchers(HttpMethod.GET, "/health", "/metrics", "/error", "/favicon.ico", "/info").permitAll()
            .requestMatchers("/").permitAll()
            .anyRequest().authenticated()
        )
        .addFilterBefore(new RolesToRightsConverterFilter(s3RSpringConfig), BasicAuthenticationFilter.class)
        .addFilterAfter(new Slf4jMDCFilter(authService, tracingService), RolesToRightsConverterFilter.class)
        .oauth2ResourceServer(oauth2 -> oauth2
            .jwt(jwt -> jwt
                .jwtAuthenticationConverter(new AadJwtBearerTokenAuthenticationConverter())
            )
        );

    return http.build();
}

原因说明

配置oauth2ResourceServer后,OAuth2资源服务器的过滤器会优先拦截未携带有效JWT的请求,直接抛出AuthenticationException,跳过了默认的匿名认证流程。显式添加.anonymous()可以确保匿名认证逻辑被正确触发,同时permitAll规则会直接放行匹配的请求,不会进入认证拦截环节。

另外,用Spring Security 6推荐的lambda形式编写authorizeHttpRequests,并合并相同HTTP方法的请求匹配规则,能让配置更简洁清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:25:19