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

Keycloak与Wildfly集成:访问令牌过期后会话中断问题求助

解决方案

要解决Access Token到期后用户被迫重新登录的问题,核心是启用自动令牌刷新功能,利用Keycloak的Refresh Token在后台自动获取新的Access Token,维持会话直到30分钟的会话过期时间点。

1. 修改OpenID认证机制注解

在@OpenIdAuthenticationMechanismDefinition中添加useRefreshToken = true和tokenStore = TokenStore.SESSION配置,启用自动刷新并将令牌存储在Web会话中:

@OpenIdAuthenticationMechanismDefinition(
        providerURI = "${openIdConfig.providerUrl}",
        clientId = "${openIdConfig.clientId}",
        clientSecret = "${openIdConfig.clientSecret}",
        redirectURI = "${openIdConfig.redirectUrl}",
        claimsDefinition = @ClaimsDefinition(callerGroupsClaim = "roles"),
        logout = @LogoutDefinition(redirectURI = "/logout.html", notifyProvider = true),
        useRefreshToken = true, // 启用自动刷新Access Token
        tokenStore = TokenStore.SESSION // 将令牌存储在HttpSession中,确保刷新时能获取Refresh Token
)

2. 检查Keycloak客户端配置

登录Keycloak管理控制台,针对你的客户端完成以下配置检查:

  • Access Type:确保设置为confidential(因为你的代码使用了clientSecret,只有该类型支持Refresh Token流程)
  • Refresh Token Lifespan:在客户端的「Advanced」标签下,将该值设置为30分钟,与你期望的会话过期时间保持一致
  • Credentials:确认客户端密钥与代码中clientSecret配置的一致

3. 同步Web应用会话超时时间

在web.xml中添加或修改会话超时配置,确保Web应用的会话有效期与Keycloak的Refresh Token有效期匹配:

<session-config>
    <session-timeout>30</session-timeout> <!-- 单位:分钟 -->
</session-config>

原理说明

启用useRefreshToken后,当Access Token(默认5分钟)即将到期时,Wildfly的OpenID认证机制会自动使用存储在会话中的Refresh Token向Keycloak请求新的Access Token,整个过程对用户完全透明。只要Refresh Token未过期(30分钟)且Web会话仍有效,用户就无需重新登录,直到两者任一到期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:37:21