无用户交互的Java服务对接KeyCloak身份认证的实现方案咨询
方案1:新建带密钥的Client(推荐优先使用)
这是服务到服务无终端用户调用场景的标准实现,完全匹配你的需求,不需要浏览器交互也不需要终端用户参与。
Keycloak侧配置步骤
- 进入目标Realm,选择「Clients」→「Create client」
- Client type选择
OpenID Connect,填写自定义Client ID后进入下一步 - 开启「Client authentication」选项,关闭「Standard flow」「Implicit flow」「Direct access grants」所有和终端用户相关的授权流,仅保留「Service accounts roles」后保存
- 切换到「Credentials」标签页,复制生成的Client Secret,后续Java侧配置需要用到
- 切换到「Service accounts roles」标签页,给这个Client分配调用目标REST API需要的角色/权限,逻辑和给终端用户分配权限完全一致
Java侧实现
可以直接调用Keycloak的token接口获取访问凭证,也可以用成熟的OAuth2客户端框架简化开发,两种示例如下:
普通Java项目实现(基于OkHttp)
import okhttp3.*; import org.json.JSONObject; import java.io.IOException; public class KeycloakClientCredDemo { private final OkHttpClient okHttpClient = new OkHttpClient(); // 缓存access token,避免每次调用都申请新凭证 private String cachedAccessToken; private long tokenExpireTime; public String getValidAccessToken() throws IOException { // 缓存未过期直接返回 if (System.currentTimeMillis() < tokenExpireTime) { return cachedAccessToken; } String tokenUrl = "https://<你的Keycloak域名>/realms/<你的Realm名称>/protocol/openid-connect/token"; RequestBody formBody = new FormBody.Builder() .add("grant_type", "client_credentials") .add("client_id", "<你新建的Client ID>") .add("client_secret", "<你复制的Client Secret>") .build(); Request request = new Request.Builder() .url(tokenUrl) .post(formBody) .build(); try (Response response = okHttpClient.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("申请Token失败:" + response.code()); } JSONObject resJson = new JSONObject(response.body().string()); cachedAccessToken = resJson.getString("access_token"); // 提前10秒过期,避免边界问题 tokenExpireTime = System.currentTimeMillis() + (resJson.getLong("expires_in") - 10) * 1000; return cachedAccessToken; } } }
拿到access token后,调用目标受保护API时,在请求头添加Authorization: Bearer ${access_token}即可。
Spring Boot项目实现
直接用Spring Security OAuth2客户端自动处理token的申请、缓存、刷新逻辑,无需手动编码:
spring: security: oauth2: client: registration: keycloak-service: client-id: <你新建的Client ID> client-secret: <你复制的Client Secret> authorization-grant-type: client_credentials scope: openid provider: keycloak-service: token-uri: https://<你的Keycloak域名>/realms/<你的Realm名称>/protocol/openid-connect/token
方案2:沿用现有Client生成永久Offline Token(可行但不推荐)
技术上可以实现,但存在明显安全隐患:offline token一旦泄露,攻击者可以长期持有权限访问API,且永久有效没有自动过期的兜底机制,仅建议在临时场景下使用。
Keycloak侧配置步骤
- 确认现有Client开启了「Direct access grants」流,且「Offline Access」scope已启用
- 新建专属服务账号,分配调用API需要的权限
Java侧使用流程
首先申请一次永久有效的offline token:
// 首次申请offline token,只需执行一次,拿到后可以长期存储使用 public String getOfflineToken() throws IOException { String tokenUrl = "https://<你的Keycloak域名>/realms/<你的Realm名称>/protocol/openid-connect/token"; RequestBody formBody = new FormBody.Builder() .add("grant_type", "password") .add("client_id", "<现有Client ID>") // 如果现有Client是confidential类型,需要额外加client_secret参数 .add("username", "<专属服务账号用户名>") .add("password", "<专属服务账号密码>") .add("scope", "offline_access") .build(); Request request = new Request.Builder().url(tokenUrl).post(formBody).build(); try (Response response = okHttpClient.newCall(request).execute()) { JSONObject resJson = new JSONObject(response.body().string()); // 这个refresh_token就是永久有效的offline token return resJson.getString("refresh_token"); } }
后续需要调用API时,用存储的offline token刷新获取access token即可:
public String getAccessTokenByOfflineToken(String offlineToken) throws IOException { String tokenUrl = "https://<你的Keycloak域名>/realms/<你的Realm名称>/protocol/openid-connect/token"; RequestBody formBody = new FormBody.Builder() .add("grant_type", "refresh_token") .add("client_id", "<现有Client ID>") .add("refresh_token", offlineToken) .build(); Request request = new Request.Builder().url(tokenUrl).post(formBody).build(); try (Response response = okHttpClient.newCall(request).execute()) { JSONObject resJson = new JSONObject(response.body().string()); return resJson.getString("access_token"); } }
注意:使用该方案时,offline token必须存储在安全的保密配置中心,禁止硬编码在代码或明文配置文件中,且需要定期手动轮换降低泄露风险。
内容的提问来源于stack exchange,提问作者Meir Maor
相关产品推荐
相关产品推荐

