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

pre*_*ent 14 python api keycloak

如何通过 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"})
Run Code Online (Sandbox Code Playgroud)

我总是收到 401 错误。

我做错了什么?

xar*_*aiz 8

您无法获得client_secret公共客户。你的客户应该有 'access_type` = 'confidential'

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

秘密

PS可以通过另一个客户端client_secret使用 API 进行检索(它应该具有客户端信息视图的角色)


rav*_*iru 7

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

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

您可以使用此 api 获取 id ,它返回 ClientRepresentation 列表,其中包含IdclientId,使用Id

GET /{realm}/clients

`


小智 4

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

  1. 你需要一个令牌。您可以使用 OpenID 生成(请参阅文档)。
  2. 使用令牌(通过标头授权),您可以向 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)
Run Code Online (Sandbox Code Playgroud)

向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"})
Run Code Online (Sandbox Code Playgroud)