如何通过 Keycloak API 获取客户端密码?

How to get client secret via Keycloak API?

如何通过 Keycloak 获取客户端密钥 API?

在我看到的文档中:

GET /admin/realms/{realm}/clients/{id}/client-secret

我的代码如下:

data = {
    "grant_type" : 'password',
    "client_id" : 'myclientid',
    "username" : 'myusername',
    "password" : 'mypassword'
}
response = requests.get("https://mylink.com/auth/admin/realms/{myrealm}/clients/{myclientid}/client-secret", data=data, headers= {"Content-Type": "application/json"})

我总是收到 401 错误。

我做错了什么?

URL中的

{id}不是clientId,它不同于clientId。 它是 keycloak 唯一 ID(即 uuid),类似于 628e4b46-3d79-454f-9b1c-e07e86ee7615

GET /admin/realms/{realm}/clients/{id}/client-secret

您可以使用此 api 获取 ID,其中 returns ClientRepresentation 列表包含 IdclientId, 使用 Id

GET /{realm}/clients

`

我认为你的身份验证不起作用。

  1. 您需要令牌。您可以使用 OpenID 生成(参见 docs)。
  2. 有了token(通过header授权),就可以向API发起请求了。

示例:

获取令牌

data = {"username": "username", "password": "password",
        "client_id": "client_id", "client_secret": "client_secret", 
        "grant_type": "password"}

token = request.post("https://{server-url}/"realms/{realm-name}/protocol/openid-connect/token", data=data)

请求API

response = requests.get("https://mylink.com/auth/admin/realms/{myrealm}/clients/{myclientid}/client-secret", data=data, headers= {"Authorization": "Bearer " + token.get('access_token'), "Content-Type": "application/json"})

您无法为 public 个客户获得 client_secret。你的客户应该有 'access_type` = 'confidential'

  1. 转到领域管理面板的 CLIENTS 部分 (<protocol>://<host>:<port>/auth/admin/master/console/#/realms/<your realm>/clients/<your client code>)
  2. 将访问类型更改为 confidential
  3. 按'SAVE'
  4. 转到“凭据”选项卡
  5. 确保 'Client Authenticator' = 'Client Id and Secret'
  6. 瞧!这是您的客户机密:

更新 P.S。 client_secret 使用 API 检索是 通过另一个客户端 (应该对客户端信息视图有作用)

除了@ravthiru 的回复之外,您还可以从管理控制台的 'Instalation' 选项卡中检索客户端密码,select 格式类似于 JSON 和客户端-秘密将在 credentials.secret