The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Using Keycloak Admin Client

The Quarkus Keycloak Admin Client and its reactive twin support Keycloak Admin Client which can be used to configure a running Keycloak server.

This guide demonstrates how you can leverage the Quarkus ArC and inject the admin client to your Quarkus application, as well as how to create it directly in the application code.

To learn more about the Keycloak Admin Client, please refer to its reference guide.

Pré-requisitos

Para concluir este guia, você precisa:

  • Cerca de 15 minutos

  • Um IDE

  • JDK 17+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.9.9

  • Um container runtime instalado (Docker ou Podman)

  • Opcionalmente, o Quarkus CLI se você quiser usá-lo

  • Opcionalmente, Mandrel ou GraalVM instalado e configurado apropriadamente se você quiser criar um executável nativo (ou Docker se você usar uma compilação de contêiner nativo)

  • Keycloak

Creating the Project

Primeiro, precisamos de um novo projeto. Crie um novo projeto com o seguinte comando:

CLI
quarkus create app org.acme:security-keycloak-admin-client \
    --extension='keycloak-admin-rest-client,rest-jackson' \
    --no-code
cd security-keycloak-admin-client

Para criar um projeto Gradle, adicione a opção --gradle ou --gradle-kotlin-dsl.

Para obter mais informações sobre como instalar e usar a CLI do Quarkus, consulte o guia Quarkus CLI.

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:3.16.3:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=security-keycloak-admin-client \
    -Dextensions='keycloak-admin-rest-client,rest-jackson' \
    -DnoCode
cd security-keycloak-admin-client

Para criar um projeto Gradle, adicione a opção '-DbuildTool=gradle' ou '-DbuildTool=gradle-kotlin-dsl'.

Para usuários do Windows:

  • Se estiver usando cmd, (não use barra invertida '\' e coloque tudo na mesma linha)

  • Se estiver usando o Powershell, envolva os parâmetros '-D' entre aspas duplas, por exemplo, '"-DprojectArtifactId=security-keycloak-admin-client"'

This command generates a project which imports the keycloak-admin-rest-client and rest-jackson extensions.

If you already have your Quarkus project configured, you can add the keycloak-admin-rest-client and rest-jackson extensions to your project by running the following command in your project base directory:

CLI
quarkus extension add keycloak-admin-rest-client,rest-jackson
Maven
./mvnw quarkus:add-extension -Dextensions='keycloak-admin-rest-client,rest-jackson'
Gradle
./gradlew addExtension --extensions='keycloak-admin-rest-client,rest-jackson'

Isto irá adicionar o seguinte trecho no seu arquivo de build:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-keycloak-admin-rest-client</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-rest-jackson</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-keycloak-admin-rest-client")
implementation("io.quarkus:quarkus-rest-jackson")

We also are going to need a simple resource with a Keycloak injected as request scoped CDI bean.

package org.acme.keycloak.admin.client;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.representations.idm.RoleRepresentation;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import java.util.List;

@Path("/api/admin")
public class RolesResource {

        @Inject
        Keycloak keycloak; (1)

        @GET
        @Path("/roles")
        public List<RoleRepresentation> getRoles() {
            return keycloak.realm("quarkus").roles().list();
        }

}
1 Create a default Keycloak Admin Client which can perform Keycloak master realm administration tasks as an admin-cli client, such as adding new realms, clients and users.

The only configuration which is required to create this Keycloak Admin Client is a Keycloak server URL.

For example:

# Quarkus based Keycloak distribution
quarkus.keycloak.admin-client.server-url=http://localhost:8081

or

# WildFly based Keycloak distribution
quarkus.keycloak.admin-client.server-url=http://localhost:8081/auth

It is important that quarkus.keycloak.admin-client.server-url is configured if you would like to have Keycloak injected. The injection will fail if you attempt to inject Keycloak without configuring this property.

Injecting Keycloak Admin Client instead of creating it directly in the application code is a simpler and more flexible option but you can create the same admin client manually if necessary:

package org.acme.keycloak.admin.client;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.representations.idm.RoleRepresentation;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import java.util.List;

@Path("/api/admin")
public class RolesResource {

        Keycloak keycloak;

        @PostConstruct
        public void initKeycloak() {
            keycloak = KeycloakBuilder.builder()
                .serverUrl("http://localhost:8081")
                .realm("master")
                .clientId("admin-cli")
                .grantType("password")
                .username("admin")
                .password("admin")
                .build();
        }

        @PreDestroy
        public void closeKeycloak() {
            keycloak.close();
        }

        @GET
        @Path("/roles")
        public List<RoleRepresentation> getRoles() {
            return keycloak.realm("quarkus").roles().list();
        }

}

For more details consult Keycloak Admin REST API documentation.

You can configure Keycloak Admin Client to administer other realms and clients. It can use either a password or client_credentials grant to acquire an access token to call the Admin REST API which requires authorization.

If you exchange user’s credentials for the access token, here is an example configuration for the password grant type:

quarkus.keycloak.admin-client.server-url=http://localhost:8081
quarkus.keycloak.admin-client.realm=quarkus
quarkus.keycloak.admin-client.client-id=quarkus-client
quarkus.keycloak.admin-client.username=alice
quarkus.keycloak.admin-client.password=alice
quarkus.keycloak.admin-client.grant-type=PASSWORD (1)
1 Use password grant type.

An example using the client-credentials grant type needs only a minor adjustments:

quarkus.keycloak.admin-client.enabled=true
quarkus.keycloak.admin-client.server-url=http://localhost:8081
quarkus.keycloak.admin-client.realm=quarkus
quarkus.keycloak.admin-client.client-id=quarkus-client
quarkus.keycloak.admin-client.client-secret=secret
quarkus.keycloak.admin-client.username= # remove default username
quarkus.keycloak.admin-client.password= # remove default password
quarkus.keycloak.admin-client.grant-type=CLIENT_CREDENTIALS (1)
1 Use client_credentials grant type.
Note that the OidcClient can also be used to acquire tokens.

Configuring TLS

To configure a TLS connection for the Keycloak Admin Client, use the TLS Registry extension and point the Keycloak Admin Client to respective TLS configuration. For example, you can configure mutual TLS (mTLS) like this:

quarkus.keycloak.admin-client.tls-configuration-name=kc-mtls
quarkus.tls.kc-mtls.key-store.p12.path=client-keystore.p12
quarkus.tls.kc-mtls.key-store.p12.password=secret
quarkus.tls.kc-mtls.trust-store.p12.path=client-truststore.p12
quarkus.tls.kc-mtls.trust-store.p12.password=secret

Testando

The preferred approach for testing Keycloak Admin Client against Keycloak is Dev Services for Keycloak. Dev Services for Keycloak will start and initialize a test container. Then, it will create a quarkus realm and a quarkus-app client (secret secret) and add alice (admin and user roles) and bob (user role) users, where all of these properties can be customized.

For example, by default, a test container will be available at a randomly allocated port but you can make both Keycloak Admin Client and the container use the same port as follows:

%test.quarkus.keycloak.devservices.port=${kc.admin.port.test:45180} (1)
%test.quarkus.keycloak.admin-client.server-url=http://localhost:${kc.admin.port.test:45180}/ (2)
1 Configure the Keycloak container to listen on the 45180 port by default
2 Configure the Keycloak Admin Client to use the same port

Quarkus Keycloak Admin Client Configuration Reference

Propriedade de Configuração Fixa no Momento da Compilação - Todas as outras propriedades de configuração podem ser sobrepostas em tempo de execução.

Configuration property

Tipo

Padrão

Set to true if Keycloak Admin Client injection is supported.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_ENABLED

Show more

boolean

true

Keycloak server URL, for example, https://host:port. If this property is not set then the Keycloak Admin Client injection will fail - use org.keycloak.admin.client.KeycloakBuilder to create it instead.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_SERVER_URL

Show more

string

Realm.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_REALM

Show more

string

master

Client id.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_CLIENT_ID

Show more

string

admin-cli

Client secret. Required with a client_credentials grant type.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_CLIENT_SECRET

Show more

string

Username. Required with a password grant type.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_USERNAME

Show more

string

admin

Password. Required with a password grant type.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_PASSWORD

Show more

string

admin

OAuth 2.0 Access Token Scope.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_SCOPE

Show more

string

OAuth Grant Type.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_GRANT_TYPE

Show more

password, client-credentials

password

The name of the TLS configuration to use.

If a name is configured, it uses the configuration from quarkus.tls.<name>.* If a name is configured, but no TLS configuration is found with that name then an error will be thrown.

The default TLS configuration is not used by default.

Environment variable: QUARKUS_KEYCLOAK_ADMIN_CLIENT_TLS_CONFIGURATION_NAME

Show more

string

Conteúdo Relacionado