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

如何通过Keycloak REST端点获取用户最后登录会话详情?

通过Keycloak REST端点获取用户最后登录会话详情

要获取用户的最后登录会话详情,你可以通过调用Keycloak的OpenID Connect Token端点,结合UMA授权类型来实现。下面是具体的实现逻辑和完整代码示例:

核心步骤

  • 配置请求参数:指定受众为你的客户端ID,授权类型使用UMA Grant Type
  • 设置请求头:携带Content-Type和有效的Bearer访问令牌
  • 构建端点URL:替换实际的Keycloak地址和领域名称
  • 发送POST请求:以表单形式提交参数并处理响应

示例代码

// 构建请求参数
StringBuilder builder = new StringBuilder();
builder.append(OAuth2Constants.AUDIENCE + "=" + clientId + "&");
builder.append(OAuth2Constants.GRANT_TYPE + "=" + OAuth2Constants.UMA_GRANT_TYPE + "&");

// 设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authorization", "Bearer " + accessToken);

// 构建Keycloak请求URL
String realmName = "your-realm-name"; // 替换为你的实际领域名称
String keycloakURL = "http://10.10.8.113:10004/auth/realms/{realm}/protocol/openid-connect/token";
keycloakURL = keycloakURL.replace("{realm}", realmName);

// 发送POST请求
HttpURLConnection httpURLConnection = null;
OutputStreamWriter outputStreamWriter = null;
try {
    URL url = new URL(keycloakURL);
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoOutput(true);

    // 添加请求头
    if (headers != null && headers.size() > 0) {
        Iterator<Map.Entry<String, String>> itr = headers.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry<String, String> entry = itr.next();
            httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    // 写入请求参数
    outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), StandardCharsets.UTF_8);
    outputStreamWriter.write(builder.toString());
    outputStreamWriter.flush();

    // 这里可以添加响应处理逻辑,读取返回的会话详情
    // 示例解析逻辑:
    // BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
    // String line;
    // StringBuilder response = new StringBuilder();
    // while ((line = reader.readLine()) != null) {
    //     response.append(line);
    // }
    // reader.close();
    // 解析response字符串获取最后登录会话信息
} catch (IOException e) {
    e.printStackTrace();
} finally {
    // 关闭资源
    try {
        if (outputStreamWriter != null) outputStreamWriter.close();
        if (httpURLConnection != null) httpURLConnection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

注意事项

  • 确保accessToken是具有足够权限的有效令牌,需具备访问目标用户会话信息的权限
  • 替换代码中的clientId、realmName为你Keycloak实例中的实际值
  • 响应为JSON格式,你可以通过解析响应体提取最后登录时间、会话ID等详情

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:02:03