如何从 Keycloak REST API 获取用户 - Keycloak API 响应 403

How to get users from Keycloak REST API - Keycloak API response 403

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

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

然后我使用授权中的令牌调用此端点:/admin/realms/master/users header,但我收到 403 状态代码,但我不明白为什么。

谢谢

通常:403 = 您无权执行请求的操作(在此特定情况下无法查看用户)。您需要为使用的 user/client 定义 Client Roles (realm-management) 并分配正确的角色(在本例中为 view-users 角色):

Keycloak 17+ UI:

或 Keycloak 17+ UI - 启用 Service Accounts Enabled 的客户端:

Keycloak 17- UI:

您需要两个步骤

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

  • 第二次使用访问令牌调用管理员 rest api,将 Bearer 设置为前缀 授权header.

# 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'