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

在Keycloak中通过curl从OpenID配置获取JWT及用户信息的完整步骤

Keycloak下通过curl完成OpenID配置获取到用户信息的完整步骤

1. 获取OpenID配置信息

你已完成此步骤,对应命令:

curl --location --request GET 'http://localhost:8080/auth/realms/my-realm/.well-known/openid-configuration'

返回结果里需重点关注两个核心端点:

  • token_endpoint:用于申请JWT令牌
  • userinfo_endpoint:用于获取用户信息

2. 获取JWT访问令牌

根据Keycloak支持的授权类型,提供两种常用调用方式:

方式一:密码授权模式(测试场景适用,直接用用户账号密码获取)

需提前准备:

  • 客户端ID(需在Keycloak控制台创建并开启密码授权类型)
  • 客户端密钥(若客户端开启了Client Authentication则必填,否则可省略)
  • 目标用户的账号和密码

执行命令:

curl --location --request POST 'http://localhost:8080/auth/realms/my-realm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'client_id=你的客户端ID' \
--data-urlencode 'client_secret=你的客户端密钥' \ # 未开启客户端认证则删除此行
--data-urlencode 'username=你的用户名' \
--data-urlencode 'password=你的密码' \
--data-urlencode 'scope=openid profile email'

返回结果中,access_token就是后续调用用户信息接口所需的令牌,refresh_token可用于过期后刷新令牌。

方式二:客户端凭证模式(服务间调用适用,无用户上下文)

适合服务端之间的身份认证,无需用户账号密码:

curl --location --request POST 'http://localhost:8080/auth/realms/my-realm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=你的客户端ID' \
--data-urlencode 'client_secret=你的客户端密钥'

3. 使用访问令牌获取用户信息

拿到access_token后,调用用户信息端点:

curl --location --request GET 'http://localhost:8080/auth/realms/my-realm/protocol/openid-connect/userinfo' \
--header 'Authorization: Bearer 你的access_token值'

返回结果会包含用户的基础信息,比如preferred_username、email、name等(具体内容取决于请求时的scope和用户属性配置)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:20:37