Dula
Dula

Reputation: 1436

Can't create Role using Keycloak REST API

I'm trying to add a Role to my realm in Keycloak but it's giving me a bad request response. My steps:

  1. Get a token using:
 curl -X POST "http://localhost:8180/auth/realms/master/protocol/openid-connect/token" \                                                                 
 -H 'Content-Type: application/x-www-form-urlencoded' \
 -d 'username=admin&password=admin&grant_type=password&client_id=admin-cli'
  1. Get the client ID using:
curl -X GET http://localhost:8180/auth/admin/realms/my-realm/clients?clientId=my-client \
 -H "Authorization: Bearer "$access_token \
 -H 'cache-control: no-cache'
  1. Try to add the Role using [documentation][1]:
curl -v http://localhost:8180/auth/admin/realms/my-realm/clients/[ID-from-above]/roles \
 -H "Content-Type: application.json" \
 -H "Authorization: Bearer "$access_token --data '{"name":"test-role"}'

When I issue the last command I get a bad request response. What am I doing wrong? Thank you.

https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_roles_resource

Upvotes: 1

Views: 5127

Answers (2)

s8k-37
s8k-37

Reputation: 76

You should get the token with the client-secret from the client you want to access.

token=$(
  curl -X POST "http://localhost:8180/auth/realms/master/protocol/openid-connect/token" \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'username=[USER]&password=[PASSWORD]&grant_type=password&client_id=admin-cli&client_secret=[CLIENT_SECRET]' \
  | jq -r '.access_token'
)

clientID=$(
  curl -X GET "http://localhost:8180/auth/admin/realms/vertical/clients?clientId=[CLIENT_NAME]" \
  -H "Authorization: Bearer "${token} \
  -H 'cache-control: no-cache' | jq -r '.[].id'
)

Try to use "application/json" instead of "application.json". Quotes from Authorization header should include the token.

Dont forget the -X POST in your last curl command :)

curl -X POST "http://localhost:8180/auth/admin/realms/[REALM]/clients/${clientID}/roles" \
 -H "Content-Type: application/json" \
 -H "Authorization: Bearer ${token}" \
 -d '{"name": "test-role"}'

Upvotes: 2

tryingToLearn
tryingToLearn

Reputation: 11649

You seem to be pretty close.

I was able to make realm level roles by following REST API:

enter image description here

The difference between this and your call is that you are trying to make a client level role. Do you have a specific requirement for client level role or were you just trying out?

If Realm level roles fulfill your requirement, you can use above API.

Also check this post to make sure you have followed steps correctly to set up admin Rest API.

Upvotes: 4

Related Questions