Using Keycloak Admin Client

Quarkus Keycloak 管理客户端及其响应式双胞胎支持 Keycloak 管理客户端,该客户端可用于配置正在运行的 Keycloak 服务器。

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

本指南演示了如何利用 Quarkus ArC 将管理客户端注入 Quarkus 应用程序,以及如何在应用程序代码中直接创建管理客户端。

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.

要了解有关 Keycloak 管理客户端的更多信息,请参阅其 reference guide

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

Prerequisites

Unresolved directive in security-keycloak-admin-client.adoc - include::{includes}/prerequisites.adoc[]* Keycloak

Unresolved directive in security-keycloak-admin-client.adoc - include::{includes}/prerequisites.adoc[] * Keycloak

Creating the Project

首先,我们需要一个新项目。使用以下命令创建一个新项目:

First, we need a new project. Create a new project with the following command:

Unresolved directive in security-keycloak-admin-client.adoc - include::{includes}/devtools/create-app.adoc[]

此命令生成了一个项目,它导入了 keycloak-admin-rest-clientrest-jackson 扩展。

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

如果您已经配置了您的 Quarkus 项目,则可以通过在项目基本目录中运行以下命令向您的项目添加 keycloak-admin-rest-clientrest-jackson 扩展:

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:

Unresolved directive in security-keycloak-admin-client.adoc - include::{includes}/devtools/extension-add.adoc[]

这会将以下内容添加到构建文件中:

This will add the following to your build file:

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")

我们还需要一个带有 Keycloak 的简单资源,将其注入为请求作用域 CDI Bean。

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.

创建此 Keycloak 管理客户端所需的唯一配置是 Keycloak 服务器 URL。

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

如果要注入 Keycloak ,则配置 quarkus.keycloak.admin-client.server-url 非常重要。如果您尝试在未配置此属性的情况下注入 Keycloak ,则注入失败。

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.

注入 Keycloak 管理客户端(而不是在应用程序代码中直接创建它)是一个更简单、更灵活的选择,但您可以在必要时手动创建相同的管理客户端:

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();
        }

}

有关详细信息,请参阅 Keycloak Admin REST API documentation

For more details consult Keycloak Admin REST API documentation.

您可以配置 Keycloak 管理客户端以管理其他领域和客户端。它可以使用 passwordclient_credentials 授权来获取访问令牌,以调用需要授权的管理 REST API。

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.

如果您交换用户的凭证以获取访问令牌,则以下是 password 授权类型的示例配置:

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.

使用 client-credentials 授权类型的示例只需要进行轻微调整:

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.

请注意, OidcClient 也可用于获取令牌。

Note that the OidcClient can also be used to acquire tokens.

Testing

针对 Keycloak 测试 Keycloak 管理客户端的首选方法是 Dev Services for Keycloak.Dev Services for Keycloak 将启动并初始化一个测试容器。然后,它将创建一个 quarkus 领域和一个 quarkus-app 客户端( secret 秘钥)并添加 aliceadminuser 角色)以及 bobuser 角色)用户,其中所有这些属性都可以进行定制。

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.

例如,默认情况下,一个测试容器将可用于一个随机分配的端口,但您可以使 Keycloak 管理客户端和容器使用相同的端口,如下所示:

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

Unresolved directive in security-keycloak-admin-client.adoc - include::{generated-dir}/config/quarkus-keycloak-admin-client.adoc[]