# Keycloak Management via API Access and User Creation

⚠️ This documentation is for keycloak <v20, see related ticket ⚠️

# Introduction

You may wish to programmatically manage aspects of your Keycloak setup via the Keycloak API. This is particularly useful for tasks such as:

  1. Bulk User Creation
  2. Modifying group membership
  3. Assigning roles to many users

The following instructions will show you how to configure a Keycloak Client Service Account and assign appropriate permissions required for the management task.

# Configure a Keycloak Client

Navigate to: -> Clients -> Select Client: realm-management -> Settings tab

We’re using the realm-management client here but you can configure any other client. Make sure the following options are set.

parameter value comment
Enabled true
Client Protocol openid-connect (default value)
Access Type confidential This will allow us to make a call to the token service endpoint and follow an openid login flow.
Valid Redirect URIs url url refers to base url of keycloak instance. Access Type must be set to confidential for this option to show
Service Accounts Enabled true (default value). Access Type must be set to confidential for this option to show

# Obtain Client Credentials

Navigate to: -> Clients -> Select Client: realm-management -> Credentials tab

  1. Select Client Id and Secret
  2. Click Regenerate Secret to generate a secret
  3. Keep ClientId and Secret for obtaining an access token from keycloak

parameter value comment
Client Authenticator Client Id and Secret

# Configure Service Account Roles

Navigate to: -> Clients -> Select Client: realm-management -> Service Account Roles Tab

Under Client Roles -> Select the realm-management from the dropdown menu

From here scroll through the available roles for the view-users roles. Click Add selected >> Assign additional roles if needed.

# Make API calls to the Keycloak 12 REST API

See Keycloak REST-API documentation

Provide client_id, client_secret, grant_type=”client_credentials” as x-www-form-urlencoded

  1. Make a call to the token service to obtain an access token
# Obtain an access token
curl -X POST https://<KEYCLOAK_HOST>/auth/realms/<REALM>/protocol/openid-connect/token \
    -H 'Content-type: application/x-www-form-urlencoded' \
    -d "client_id=$(KC_CLIENT_ID)" \
    -d "client_secret=$(KC_CLIENT_SECRET)" \
    -d "grant_type=$(KC_GRANT_TYPE)" | jq '.access_token'
  1. Send the token which each request
# Get keycloak users
curl -X GET https://<KEYCLOAK_HOST>/auth/admin/realms/<REALM>/users \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H 'cache-control: no-cache'