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

Spring Boot 3中如何解决Spring Security预认证拒绝访问问题?

Spring Boot 3中JWT认证出现Pre-authenticated entry point called. Rejecting access错误的解决

问题背景

我一直尽量避免用Spring Security,因为它会注入一大堆难禁用的默认配置。现在要用到JWT令牌,写了安全配置后却碰到预认证失败的问题,错误提示是Pre-authenticated entry point called. Rejecting access,不知道怎么在Boot 3应用里禁用预认证。

当前安全配置代码:

@Bean
@Throws(Exception::class)
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
    return http.csrf { it.disable() }
        .authorizeHttpRequests { it.anyRequest().authenticated() }
        .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
        .authenticationProvider(authenticationProvider())
        .build()
}

@Bean
fun authenticationProvider(): AuthenticationProvider {
    val authenticationProvider = JwtAuthenticationProvider(jwtDecoder())
    return authenticationProvider
}

@Bean
fun jwtDecoder(): JwtDecoder {
    return NimbusJwtDecoder.withPublicKey(rsaProperties.publicKey).build()
}

@Bean
fun jwtEncoder(): JwtEncoder {
    val jwk: JWK =
        RSAKey.Builder(rsaProperties.publicKey).privateKey(rsaProperties.privateKey).build()

    val jwks: JWKSource<SecurityContext> = ImmutableJWKSet(JWKSet(jwk))
    return NimbusJwtEncoder(jwks)
}

Spring Security Web调试日志:

2024-02-14T13:58:20.238-08:00 DEBUG 5308 --- [tp1468039653-29] o.s.security.web.FilterChainProxy: Securing POST /v1/ds/123456789/register
2024-02-14T13:58:20.239-08:00 DEBUG 5308 --- [tp1468039653-29] o.s.s.w.a.AnonymousAuthenticationFilter: Set SecurityContextHolder to anonymous SecurityContext
2024-02-14T13:58:20.239-08:00 DEBUG 5308 --- [tp1468039653-29] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access
2024-02-14T13:58:20.243-08:00 DEBUG 5308 --- [tp1468039653-29] o.s.security.web.FilterChainProxy        : Securing POST /error
2024-02-14T13:58:20.244-08:00 DEBUG 5308 --- [tp1468039653-29] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-02-14T13:58:20.244-08:00 DEBUG 5308 --- [tp1468039653-29] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access

解决方法

出现这个错误的核心原因是:只配置了JwtAuthenticationProvider,但没有添加JWT认证过滤器来提取并验证请求中的JWT令牌,导致Spring Security无法识别用户的认证信息,最终触发预认证入口拒绝访问。

在Spring Boot 3的Security配置中,需要显式整合JWT认证逻辑,替换默认的预认证处理流程。

修改后的安全配置

更新securityFilterChain方法,添加oauth2ResourceServer().jwt()配置,它会自动注册所需的JWT过滤器和认证逻辑,同时替换默认的预认证入口:

@Bean
@Throws(Exception::class)
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
    return http.csrf { it.disable() }
        .authorizeHttpRequests { it.anyRequest().authenticated() }
        .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
        .oauth2ResourceServer { oauth2 ->
            oauth2.jwt { jwt ->
                jwt.decoder(jwtDecoder())
            }
        }
        .exceptionHandling { exceptions ->
            // 自定义未认证时的响应,替换默认的预认证拒绝逻辑
            exceptions.authenticationEntryPoint { request, response, authException ->
                response.status = HttpServletResponse.SC_UNAUTHORIZED
                response.contentType = MediaType.APPLICATION_JSON_VALUE
                response.writer.write("{\"error\": \"未授权,请提供有效的JWT令牌\"}")
            }
        }
        .build()
}

关键说明

  1. oauth2ResourceServer().jwt():该配置自动引入JwtAuthenticationFilter,负责从请求头的Authorization: Bearer <token>中提取JWT,并用你配置的jwtDecoder验证令牌有效性,完成认证流程。
  2. 移除手动配置的JwtAuthenticationProvider:使用oauth2ResourceServer后,Spring Security会自动注册对应的认证提供者,无需手动添加。
  3. 自定义认证入口:通过exceptionHandling配置自定义的authenticationEntryPoint,替换默认的Http403ForbiddenEntryPoint,返回更友好的未授权响应,彻底解决预认证拒绝问题。

验证效果

修改配置后,携带有效JWT令牌的请求会正常完成认证;未携带令牌或令牌无效时,会触发自定义的未授权响应,不再出现Pre-authenticated entry point called. Rejecting access的日志。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:40:35