president
president

Reputation: 523

How to get client secret via Keycloak API?

How to get client secret via Keycloak API?

In documentation I see:

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

My code is the following:

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

I always get 401 error.

What do I do wrong?

Upvotes: 18

Views: 45347

Answers (4)

xardbaiz
xardbaiz

Reputation: 817

You can't get client_secret for public clients. Your client should have 'access_type` = 'confidential'

  1. Go to CLIENTS section of your realm admin panel (<protocol>://<host>:<port>/auth/admin/master/console/#/realms/<your realm>/clients/<your client code>)
  2. Change Access Type to confidential confidential
  3. Press 'SAVE'
  4. Go to the "Credentials" tab
  5. Make sure that 'Client Authenticator' = 'Client Id and Secret'
  6. Voila! Here's your client secret:

secret

UPD P.S. client_secret retrieving using API is possible through another client (which should have role for client info view)

Upvotes: 16

Edorka
Edorka

Reputation: 1811

In addition to the reponse by @ravthiru you can retrieve the client-secret from the 'Instalation' tab on the admin console, select a format like JSON and the client-secret would be in credentials.secret

Upvotes: 0

I think your authentication it's not working.

  1. You need a token. You can generate using OpenID (see docs).
  2. With the token (by header Authorization), you can do request to API.

Example:

Get the token

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)

Request to 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"})

Upvotes: 4

ravthiru
ravthiru

Reputation: 9633

{id} in the URL is not clientId, it is different from clientId. it is keycloak unique id ( which is uuid ) some thing like 628e4b46-3d79-454f-9b1c-e07e86ee7615

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

You can get id using this api , where it returns list of ClientRepresentation, which has both Id and clientId, use Id

GET /{realm}/clients

`

Upvotes: 8

Related Questions