如何通过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错误。

我做错了什么?


问题答案:

我认为您的身份验证无效。

  1. 您需要一个令牌。您可以使用OpenID生成(请参阅docs)。
  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)

要求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"})