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

KeyCloak 15.0.2集成Spring Boot后首次403后续合法用户访问仍报错求助

问题根因

你当前的配置采用了适配带会话的传统Web应用的会话认证策略,而你部署的是bearer-only类型的Keycloak资源服务,本身不需要维护服务端会话。第一次无Authorization头访问时,Spring Security会将匿名身份信息缓存到会话中,后续请求会优先读取会话内存储的匿名身份,即使用户传入合法Access Token也不会触发重新校验,因此持续返回403错误。

修复方案

1. 替换会话认证策略实现

将原有的RegisterSessionAuthenticationStrategy替换为适用于无状态Bearer服务的NullAuthenticatedSessionStrategy,避免会话注册逻辑。

2. 配置会话为无状态模式

在HttpSecurity规则中显式指定会话创建策略为STATELESS,完全禁用服务端会话存储,每次请求独立校验Token。

3. 补全Keycloak过滤器链加载逻辑

原有配置未调用父类configure(http)方法,导致Keycloak默认的认证过滤器没有生效,需要补充该调用。

修改后的完整配置类代码如下:

import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@KeycloakConfiguration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class ResourceServiceConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        // 替换为无状态会话策略
        return new NullAuthenticatedSessionStrategy();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
        // 可选配置:如果你的Keycloak角色没有ROLE_前缀,可打开下方注释自动添加前缀,避免角色匹配失败
        // mapper.setPrefix("ROLE_");
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(mapper);
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 必须调用父类方法加载Keycloak认证过滤器链
        super.configure(http);
        http.sessionManagement()
                // 完全禁用服务端会话
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .anyRequest().permitAll();
        http.csrf().disable();
    }
}
验证效果

配置修改后重启应用,先不带Authorization头访问接口得到403,再传入合法Access Token访问即可正常得到200响应,无需重启应用。

内容的提问来源于stack exchange,提问作者Said SB-Coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:45:02