Skip to content

Access Token Management

Keycloak comes with a fully functional Admin REST API with all features provided by the Admin Console. To invoke the API you need to obtain an access token with the appropriate permissions.

Please refer to official docs for more details on how to setup Service Account.

Configure Service Account

We need to create a Service Account in master realm, configure a special Audience Mapper that adds security-admin-console audience to the token, and assign Service Account Role - "admin".

Create a service account client called "admin-api" and enable Client Authentication and Service Account Roles.

Then, download adapter config from Keycloak and added it to "appsettings.json" to "Keycloak section. Here is how it looks like:

json
{
  "Keycloak": {
    "realm": "master",
    "auth-server-url": "http://localhost:8080/",
    "ssl-required": "none",
    "resource": "admin-api",
    "credentials": {
      "secret": "k9LYTWKfbNOyfzFt2ZZsFl3Z4x4aAecf"
    },
    "confidential-port": 0
  }
}

💡 See admin-api export file if you want to import it and see how it looks in Keycloak.

Add Token Management

Luckily, there is a production-ready library called DuendeSoftware/Duende.AccessTokenManagement that retrieves and caches tokens.

To install it run:

bash
dotnet add package Duende.AccessTokenManagement

See the docs on how to configure and use this library to use Service Accounts.

Example

cs
var options = configuration.GetKeycloakOptions<KeycloakAdminClientOptions>()!;

services.AddDistributedMemoryCache();
services
    .AddClientCredentialsTokenManagement()
    .AddClient(
        tokenClientName,
        client =>
        {
            client.ClientId = options.Resource;
            client.ClientSecret = options.Credentials.Secret;
            client.TokenEndpoint = options.KeycloakTokenEndpoint;
        }
    );

services
    .AddKeycloakAdminHttpClient(configuration)
    .AddClientCredentialsTokenHandler(tokenClientName);

var sp = services.BuildServiceProvider();
var client = sp.GetRequiredService<IKeycloakRealmClient>();

var realm = await client.GetRealmAsync("Test");