How to set up a client scope from kcadm?

I have a need to create some constant information to be added to a JWT for everything in a certain realm. I managed to get it set up manually by doing the following for each item:

  • Creating a Client Scope for the item
  • In Client>Client Scopes I added the scope to the Assigned Default
  • Added a protocol mapper to Client Mapper type = Hardcoded Claim

But I need to script this to make it more easily repeatable across multiple realms. I’m fine with using kcadm to create a realm and a client and a user but I don’t see anything about creating client scopes. Ideally it is just some kcadm commands I haven’t found yet. I’m, using KC 11.0.0

So far I have got the first step done:

./ create -x “client-scopes” -r $REALM_NAME -s name=tenantSecret

But the other two are eluding me. I’ve been looking at the API lots, tried lots of things that give me errors. Does anyone know how to do this?

I managed to figure this one out myself. This is the resulting script:

# Create a Realm for the tenant (use lower case for Realm Name)
./ create realms -s realm=$REALM_NAME -s enabled=true
# create  Client Scope
./ create -x "client-scopes" -r $REALM_NAME -s name=tenantId -s protocol=openid-connect

./ create clients -r $REALM_NAME \
	-s clientId=my-client \
	-s enabled=true

CLIENT_ID=`./ get -x "clients" -r $REALM_NAME | jq '.[] | select(.clientId == "my-client") | .id'| sed -r 's/^"|"$//g'`
./ create clients/$CLIENT_ID/protocol-mappers/models -r $REALM_NAME \
	-s name=tenantId -s protocol=openid-connect \
	-s protocolMapper=oidc-hardcoded-claim-mapper \
	-s config="{\"claim.value\" : \"$REALM_NAME\",\"\" : \"tenantId\",\"jsonType.label\" : \"String\",\"access.token.claim\" : \"true\"}"

./ update clients/$CLIENT_ID  -r $REALM_NAME --body "{\"defaultClientScopes\": [\"tenantId\"]}"

The resulting evaluation in Clients>my-client>Client Scopes for my test user shows the tenantId value in the access token.


Appreciate the courtesy mate!

I’ve used the -f flag in the create client command to create the client by passing a JSON file to the command.
However, the update client command isn’t updating my client with the newly created client scopes when the updated file is passed to it via the -f flag.
Anybody know how do I update a client by passing the JSON file as a parameter?

1 Like

I confirm, keycloak:11.0.2 doesn’t update client with update client, it doesn’t error out either…

1 Like

That’s right Andriy,

I’ve used the command given below to update the client scopes: update http://keycloak:8080/auth/admin/realms/${REALM_NAME}/clients/${CLIENT_ID}/default-client-scopes/${CLIENT-SCOPE_ID}