如何从 Keycloak REST API 获取用户?

Posted

技术标签:

【中文标题】如何从 Keycloak REST API 获取用户?【英文标题】:How to get users from Keycloak REST API? 【发布时间】:2019-08-27 08:39:12 【问题描述】:

您好,我正在尝试使用 Keycloak API,但我不太了解它是如何工作的。我想获得一个领域的所有用户。所以我首先使用这个端点获取一个令牌:/realms/master/protocol/openid-connect/token,请求正文中有这个参数:

client_id grant_type 用户名 密码 client_secret

第一个问题是:我应该使用什么客户端?

然后我使用 Authorization 标头中的令牌调用此端点:/admin/realms/master/users,但我得到一个 403 状态代码,我不明白为什么。

谢谢

【问题讨论】:

【参考方案1】:

403 = 可能您没有查看用户的权限。您需要为已使用的用户定义Client Roles 并分配view-users 角色:

【讨论】:

你能看看我的 Keycloak 相关问题***.com/q/70376766/2886891 吗?谢谢。【参考方案2】:

你需要两个步骤

首先从主域的 admin-cli 客户端获取访问令牌

第二次使用访问令牌调用admin rest api,将Bearer设置为前缀 授权标头。

# get an access token
curl -X POST \
  https://<HOST>/auth/realms/master/protocol/openid-connect/token \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'cache-control: no-cache' \
  -d 'grant_type=password&username=<USERNAME>l&password=<PASSWORD>&client_id=admin-cli'

# get all users of gateway realm, use the token from above and use Bearer as prefix
curl -X GET \
  https://<HOST>/auth/admin/realms/gateway/users \
  -H 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkI...' \
  -H 'cache-control: no-cache'

【讨论】:

以上是关于如何从 Keycloak REST API 获取用户?的主要内容,如果未能解决你的问题,请参考以下文章