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

OpenID Connect (OIDC) を使用したBearer Token認可によるサービスアプリケーションの保護

このガイドでは、Quarkus OpenID Connect (OIDC) Extensionを使用して、Bearer TokenがOpenID Connectや Keycloak などのOAuth 2.0準拠の認可サーバーによって発行されるBearer Token認可を使用して、JAX-RSアプリケーションを保護する方法を説明します。

Bearer Token認可とは、Bearer Tokenの存在と有効性に基づいて HTTP リクエストを認可するプロセスで、HTTP リソースにアクセスできるかどうかだけでなく、呼び出しの対象を決定するための価値のある情報を提供します。

次の図は、Quarkus のBearer Token認可メカニズムの概要を示しています。

Bearer Token Authorization
Figure 1. QuarkusにおけるBearer Tokenによる認可メカニズムとシングルページアプリケーション
  1. Quarkusサービスでは、OpenID Connectプロバイダーから検証キーを取得します。検証キーは、Bearerアクセストークンの署名を検証するために使用されます。

  2. Quarkusユーザーは、シングルページアプリケーションにアクセスします。

  3. シングルページアプリケーションでは、Authorization Code Flowを使用してユーザーを認証し、OpenID Connectプロバイダーからトークンを取得します。

  4. シングルページアプリケーションでは、アクセストークンを使用して、Quarkusサービスからサービスデータを取得します。

  5. Quarkusサービスは、検証キーを使用してBearerアクセストークンの署名を検証し、トークンの有効期限やその他のクレームをチェックし、トークンが有効であればリクエストを続行させ、サービス応答をシングルページアプリケーションに返します。

  6. シングルページアプリケーションは、同じデータをQuarkusユーザーに返します。

Bearer Token Authorization
Figure 2. Javaまたはコマンドラインクライアントを使用したQuarkusのBearer Token認可メカニズム
  1. Quarkusサービスでは、OpenID Connectプロバイダーから検証キーを取得します。検証キーは、Bearerアクセストークンの署名を検証するために使用されます。

  2. クライアントは、OpenID Connectプロバイダからアクセストークンを取得するために、クライアントIDとシークレットを必要とする client_credentials 、またはクライアントID、シークレット、ユーザー名、パスワードも必要とするpassword grantを使用します。

  3. クライアントはアクセストークンを使用して、Quarkusサービスからサービスデータを取得します。

  4. Quarkusサービスは、検証キーを使用してBearerアクセストークンの署名を検証し、トークンの有効期限やその他のクレームをチェックし、トークンが有効であればリクエストの実行を許可し、サービスレスポンスをクライアントに返します。

OpenID Connect認可コードフローを使用してユーザーの認証と認可を行う必要がある場合は、 Using OpenID Connect to Protect Web Applications を参照してください。また、KeycloakとBearer Tokenを使用する場合は、 Using Keycloak to Centralize Authorization を参照してください。

マルチテナントへの対応方法については、 OpenID Connect (OIDC) マルチテナンシーの使用 ガイドをお読みください。

クイックスタート

前提条件

このガイドを完成させるには、以下が必要です:

  • 約15分

  • IDE

  • JDK 11+ がインストールされ、 JAVA_HOME が適切に設定されていること

  • Apache Maven 3.8.6

  • 動作するコンテナランタイム(Docker, Podman)

  • 使用したい場合は、 Quarkus CLI

  • ネイティブ実行可能ファイルをビルドしたい場合、MandrelまたはGraalVM(あるいはネイティブなコンテナビルドを使用する場合はDocker)をインストールし、 適切に設定していること

  • jq tool

アーキテクチャ

この例では、2つのエンドポイントを提供する非常にシンプルなマイクロサービスを構築しています。

  • /api/users/me

  • /api/admin

これらのエンドポイントは保護されており、クライアントがリクエストと一緒にベアラートークンを送信している場合にのみアクセスすることができます。

ベアラートークンは、Keycloakサーバーによって発行され、トークンが発行された対象を表します。OAuth 2.0 認可サーバーであるため、トークンはユーザーの代わりに動作するクライアントも参照します。

/api/users/me エンドポイントは、有効なトークンを持つ任意のユーザーがアクセスできます。レスポンスとして、トークンに記録されている情報から取得したユーザーの詳細を含む JSON ドキュメントを返します。

/api/admin エンドポイントは RBAC (Role-Based Access Control) で保護されており、 admin ロールで許可されたユーザーのみがアクセスできます。このエンドポイントでは、 @RolesAllowed アノテーションを使用して、アクセス制約を宣言的に強制します。

ソリューション

次の章で紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。

Gitレポジトリをクローンするか git clone https://github.com/quarkusio/quarkus-quickstarts.gitアーカイブ をダウンロードします。

ソリューションは security-openid-connect-quickstart directory にあります。

Mavenプロジェクトの作成

まず、新しいプロジェクトが必要です。以下のコマンドで新規プロジェクトを作成します。

コマンドラインインタフェース
quarkus create app org.acme:security-openid-connect-quickstart \
    --stream=2.16 \
    --extension='oidc,resteasy-reactive-jackson' \
    --no-code
cd security-openid-connect-quickstart

Gradleプロジェクトを作成するには、 --gradle または --gradle-kotlin-dsl オプションを追加します。

Quarkus CLIのインストール方法や使用方法については、 Quarkus CLIガイド を参照してください。

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:2.16.12.Final:create \
    -DplatformVersion=2.16 \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=security-openid-connect-quickstart \
    -Dextensions='oidc,resteasy-reactive-jackson' \
    -DnoCode
cd security-openid-connect-quickstart

Gradleプロジェクトを作成するには、 -DbuildTool=gradle または -DbuildTool=gradle-kotlin-dsl オプションを追加します。

このコマンドは、QuarkusのOIDCの実装である oidc エクステンションをインポートして、Mavenプロジェクトを生成します。

すでにQuarkusプロジェクトが設定されている場合は、プロジェクトのベースディレクトリーで以下のコマンドを実行することで、プロジェクトに oidc エクステンションを追加することができます。

コマンドラインインタフェース
quarkus extension add 'oidc'
Maven
./mvnw quarkus:add-extension -Dextensions='oidc'
Gradle
./gradlew addExtension --extensions='oidc'

これにより、 pom.xml に以下が追加されます:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-oidc</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-oidc")

アプリケーションの記述

まずは /api/users/me エンドポイントを実装してみましょう。下のソースコードを見るとわかるように、これは通常の JAX-RS リソースです。

package org.acme.security.openid.connect;

import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

import org.jboss.resteasy.reactive.NoCache;
import io.quarkus.security.identity.SecurityIdentity;

@Path("/api/users")
public class UsersResource {

    @Inject
    SecurityIdentity securityIdentity;

    @GET
    @Path("/me")
    @RolesAllowed("user")
    @NoCache
    public User me() {
        return new User(securityIdentity);
    }

    public static class User {

        private final String userName;

        User(SecurityIdentity securityIdentity) {
            this.userName = securityIdentity.getPrincipal().getName();
        }

        public String getUserName() {
            return userName;
        }
    }
}

/api/admin エンドポイントのソースコードも非常にシンプルです。ここでの主な違いは、 admin ロールで付与されたユーザーだけがエンドポイントにアクセスできるように @RolesAllowed アノテーションを使用していることです:

package org.acme.security.openid.connect;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

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

    @GET
    @RolesAllowed("admin")
    @Produces(MediaType.TEXT_PLAIN)
    public String admin() {
        return "granted";
    }
}

SecurityIdentity のインジェクションは、 @RequestScoped@ApplicationScoped の両方のコンテキストでサポートされています。

アプリケーションの設定

OpenID Connect エクステンションを使用すると、 src/main/resources ディレクトリーに配置される application.properties ファイルを使用してアダプター設定を定義することができます。

ビルド時に固定される設定プロパティ - 他のすべての設定プロパティは実行時にオーバーライド可能

Configuration property

タイプ

デフォルト

If DevServices has been explicitly enabled or disabled. When DevServices is enabled Quarkus will attempt to automatically configure and start Keycloak when running in Dev or Test mode and when Docker is running.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_ENABLED

Show more

boolean

true

The container image name to use, for container based DevServices providers. Image with a Quarkus based distribution is used by default. Image with a WildFly based distribution can be selected instead, for example: 'quay.io/keycloak/keycloak:19.0.3-legacy'. Note Keycloak Quarkus and Keycloak WildFly images are initialized differently. By default, Dev Services for Keycloak will assume it is a Keycloak Quarkus image if the image version does not end with a '-legacy' string. Set 'quarkus.keycloak.devservices.keycloak-x-image' to override this check.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_IMAGE_NAME

Show more

string

quay.io/keycloak/keycloak:21.0.1

If Keycloak-X image is used. By default, Dev Services for Keycloak will assume a Keycloak-X image is used if the image name contains a 'keycloak-x' string. Set 'quarkus.keycloak.devservices.keycloak-x-image' to override this check which may be necessary if you build custom Keycloak-X or Keycloak images. You do not need to set this property if the default check works.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_KEYCLOAK_X_IMAGE

Show more

boolean

Indicates if the Keycloak container managed by Quarkus Dev Services is shared. When shared, Quarkus looks for running containers using label-based service discovery. If a matching container is found, it is used, and so a second one is not started. Otherwise, Dev Services for Keycloak starts a new container. The discovery uses the quarkus-dev-service-label label. The value is configured using the service-name property. Container sharing is only used in dev mode.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_SHARED

Show more

boolean

true

The value of the quarkus-dev-service-keycloak label attached to the started container. This property is used when shared is set to true. In this case, before starting a container, Dev Services for Keycloak looks for a container with the quarkus-dev-service-keycloak label set to the configured value. If found, it will use this container instead of starting a new one. Otherwise, it starts a new container with the quarkus-dev-service-keycloak label set to the specified value. Container sharing is only used in dev mode.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_SERVICE_NAME

Show more

string

quarkus

The comma-separated list of class or file system paths to Keycloak realm files which will be used to initialize Keycloak. The first value in this list will be used to initialize default tenant connection properties.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_REALM_PATH

Show more

文字列のリスト

The JAVA_OPTS passed to the keycloak JVM

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_JAVA_OPTS

Show more

string

Show Keycloak log messages with a "Keycloak:" prefix.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_SHOW_LOGS

Show more

boolean

false

Keycloak start command. Use this property to experiment with Keycloak start options, see https://www.keycloak.org/server/all-config. Note it will be ignored when loading legacy Keycloak WildFly images.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_START_COMMAND

Show more

string

The Keycloak realm name. This property will be used to create the realm if the realm file pointed to by the 'realm-path' property does not exist, default value is 'quarkus' in this case. If the realm file pointed to by the 'realm-path' property exists then it is still recommended to set this property for Dev Services for Keycloak to avoid parsing the realm file in order to determine the realm name.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_REALM_NAME

Show more

string

Indicates if the Keycloak realm has to be created when the realm file pointed to by the 'realm-path' property does not exist. Disable it if you’d like to create a realm using Keycloak Administration Console or Keycloak Admin API from io.quarkus.test.common.QuarkusTestResourceLifecycleManager.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_CREATE_REALM

Show more

boolean

true

Optional fixed port the dev service will listen to. If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_PORT

Show more

int

The Keycloak users map containing the username and password pairs. If this map is empty then two users, 'alice' and 'bob' with the passwords matching their names will be created. This property will be used to create the Keycloak users if the realm file pointed to by the 'realm-path' property does not exist.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_USERS

Show more

Map<String,String>

The Keycloak user roles. If this map is empty then a user named 'alice' will get 'admin' and 'user' roles and all other users will get a 'user' role. This property will be used to create the Keycloak roles if the realm file pointed to by the 'realm-path' property does not exist.

Environment variable: QUARKUS_KEYCLOAK_DEVSERVICES_ROLES

Show more

Map<String,List<String>>

If the OIDC extension is enabled.

Environment variable: QUARKUS_OIDC_ENABLED

Show more

boolean

true

Grant type which will be used to acquire a token to test the OIDC 'service' applications

Environment variable: QUARKUS_OIDC_DEVUI_GRANT_TYPE

Show more

client'client_credentials' grant, password'password' grant, code'authorization_code' grant, implicit'implicit' grant

The WebClient timeout. Use this property to configure how long an HTTP client used by Dev UI handlers will wait for a response when requesting tokens from OpenId Connect Provider and sending them to the service endpoint.

Environment variable: QUARKUS_OIDC_DEVUI_WEB_CLIENT_TIMEOUT

Show more

Duration

4S

Enable the registration of the Default TokenIntrospection and UserInfo Cache implementation bean. Note it only allows to use the default implementation, one needs to configure it in order to activate it, please see OidcConfig#tokenCache.

Environment variable: QUARKUS_OIDC_DEFAULT_TOKEN_CACHE_ENABLED

Show more

boolean

true

The base URL of the OpenID Connect (OIDC) server, for example, https://host:port/auth. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: https://host:port/realms/{realm} where {realm} has to be replaced by the name of the Keycloak realm.

Environment variable: QUARKUS_OIDC_AUTH_SERVER_URL

Show more

string

Enables OIDC discovery. If the discovery is disabled then the OIDC endpoint URLs must be configured individually.

Environment variable: QUARKUS_OIDC_DISCOVERY_ENABLED

Show more

boolean

true

Relative path or absolute URL of the OIDC token endpoint which issues access and refresh tokens.

Environment variable: QUARKUS_OIDC_TOKEN_PATH

Show more

string

Relative path or absolute URL of the OIDC token revocation endpoint.

Environment variable: QUARKUS_OIDC_REVOKE_PATH

Show more

string

The client-id of the application. Each application has a client-id that is used to identify the application

Environment variable: QUARKUS_OIDC_CLIENT_ID

Show more

string

The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to 20S will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped.

Environment variable: QUARKUS_OIDC_CONNECTION_DELAY

Show more

Duration

The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the connection-delay property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property.

Environment variable: QUARKUS_OIDC_CONNECTION_RETRY_COUNT

Show more

int

3

The amount of time after which the current OIDC connection request will time out.

Environment variable: QUARKUS_OIDC_CONNECTION_TIMEOUT

Show more

Duration

10S

The maximum size of the connection pool used by the WebClient

Environment variable: QUARKUS_OIDC_MAX_POOL_SIZE

Show more

int

Client secret which is used for a client_secret_basic authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive.

Environment variable: QUARKUS_OIDC_CREDENTIALS_SECRET

Show more

string

The client secret value - it will be ignored if 'secret.key' is set

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_VALUE

Show more

string

The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_PROVIDER_NAME

Show more

string

The CredentialsProvider client secret key

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_PROVIDER_KEY

Show more

string

Authentication method.

Environment variable: QUARKUS_OIDC_CREDENTIALS_CLIENT_SECRET_METHOD

Show more

basicclient_secret_basic (default): client id and secret are submitted with the HTTP Authorization Basic scheme, postclient_secret_post: client id and secret are submitted as the 'client_id' and 'client_secret' form parameters., post-jwtclient_secret_jwt: client id and generated JWT secret are submitted as the 'client_id' and 'client_secret' form parameters.

If provided, indicates that JWT is signed using a secret key

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SECRET

Show more

string

The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SECRET_PROVIDER_NAME

Show more

string

The CredentialsProvider client secret key

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SECRET_PROVIDER_KEY

Show more

string

If provided, indicates that JWT is signed using a private key in PEM or JWK format. You can use the signature-algorithm property to specify the key algorithm.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_FILE

Show more

string

If provided, indicates that JWT is signed using a private key from a key store

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_STORE_FILE

Show more

string

A parameter to specify the password of the key store file. If not given, the default ("password") is used.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_STORE_PASSWORD

Show more

string

password

The private key id/alias

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_ID

Show more

string

The private key password

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_KEY_PASSWORD

Show more

string

password

JWT audience ('aud') claim value. By default, the audience is set to the address of the OpenId Connect Provider’s token endpoint.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_AUDIENCE

Show more

string

Key identifier of the signing key added as a JWT 'kid' header

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_TOKEN_KEY_ID

Show more

string

Issuer of the signing key added as a JWT 'iss' claim (default: client id)

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_ISSUER

Show more

string

Subject of the signing key added as a JWT 'sub' claim (default: client id)

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SUBJECT

Show more

string

Signature algorithm, also used for the key-file property. Supported values: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, HS256, HS384, HS512.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_SIGNATURE_ALGORITHM

Show more

string

JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time.

Environment variable: QUARKUS_OIDC_CREDENTIALS_JWT_LIFESPAN

Show more

int

10

The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the "host" config item must be configured to enable the usage of a Proxy.

Environment variable: QUARKUS_OIDC_PROXY_HOST

Show more

string

The port number of the Proxy. Default value is 80.

Environment variable: QUARKUS_OIDC_PROXY_PORT

Show more

int

80

The username, if Proxy needs authentication.

Environment variable: QUARKUS_OIDC_PROXY_USERNAME

Show more

string

The password, if Proxy needs authentication.

Environment variable: QUARKUS_OIDC_PROXY_PASSWORD

Show more

string

Certificate validation and hostname verification, which can be one of the following values from enum Verification. Default is required.

Environment variable: QUARKUS_OIDC_TLS_VERIFICATION

Show more

requiredCertificates are validated and hostname verification is enabled. This is the default value., certificate-validationCertificates are validated but hostname verification is disabled., noneAll certificated are trusted and hostname verification is disabled.

An optional key store which holds the certificate information instead of specifying separate files.

Environment variable: QUARKUS_OIDC_TLS_KEY_STORE_FILE

Show more

path

An optional parameter to specify type of the key store file. If not given, the type is automatically detected based on the file name.

Environment variable: QUARKUS_OIDC_TLS_KEY_STORE_FILE_TYPE

Show more

string

An optional parameter to specify a provider of the key store file. If not given, the provider is automatically detected based on the key store file type.

Environment variable: QUARKUS_OIDC_TLS_KEY_STORE_PROVIDER

Show more

string

A parameter to specify the password of the key store file. If not given, the default ("password") is used.

Environment variable: QUARKUS_OIDC_TLS_KEY_STORE_PASSWORD

Show more

string

password

An optional parameter to select a specific key in the key store. When SNI is disabled, if the key store contains multiple keys and no alias is specified, the behavior is undefined.

Environment variable: QUARKUS_OIDC_TLS_KEY_STORE_KEY_ALIAS

Show more

string

An optional parameter to define the password for the key, in case it’s different from key-store-password.

Environment variable: QUARKUS_OIDC_TLS_KEY_STORE_KEY_PASSWORD

Show more

string

An optional trust store which holds the certificate information of the certificates to trust

Environment variable: QUARKUS_OIDC_TLS_TRUST_STORE_FILE

Show more

path

A parameter to specify the password of the trust store file.

Environment variable: QUARKUS_OIDC_TLS_TRUST_STORE_PASSWORD

Show more

string

A parameter to specify the alias of the trust store certificate.

Environment variable: QUARKUS_OIDC_TLS_TRUST_STORE_CERT_ALIAS

Show more

string

An optional parameter to specify type of the trust store file. If not given, the type is automatically detected based on the file name.

Environment variable: QUARKUS_OIDC_TLS_TRUST_STORE_FILE_TYPE

Show more

string

An optional parameter to specify a provider of the trust store file. If not given, the provider is automatically detected based on the trust store file type.

Environment variable: QUARKUS_OIDC_TLS_TRUST_STORE_PROVIDER

Show more

string

A unique tenant identifier. It must be set by TenantConfigResolver providers which resolve the tenant configuration dynamically and is optional in all other cases.

Environment variable: QUARKUS_OIDC_TENANT_ID

Show more

string

If this tenant configuration is enabled.

Environment variable: QUARKUS_OIDC_TENANT_ENABLED

Show more

boolean

true

The application type, which can be one of the following values from enum ApplicationType.

Environment variable: QUARKUS_OIDC_APPLICATION_TYPE

Show more

web-appA WEB_APP is a client that serves pages, usually a frontend application. For this type of client the Authorization Code Flow is defined as the preferred method for authenticating users., serviceA SERVICE is a client that has a set of protected HTTP resources, usually a backend application following the RESTful Architectural Design. For this type of client, the Bearer Authorization method is defined as the preferred method for authenticating and authorizing users., hybridA combined SERVICE and WEB_APP client. For this type of client, the Bearer Authorization method will be used if the Authorization header is set and Authorization Code Flow - if not.

service

Relative path or absolute URL of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_AUTHORIZATION_PATH

Show more

string

Relative path or absolute URL of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_USER_INFO_PATH

Show more

string

Relative path or absolute URL of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_INTROSPECTION_PATH

Show more

string

Relative path or absolute URL of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_JWKS_PATH

Show more

string

Relative path or absolute URL of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC_END_SESSION_PATH

Show more

string

Public key for the local JWT token verification. OIDC server connection will not be created when this property is set.

Environment variable: QUARKUS_OIDC_PUBLIC_KEY

Show more

string

Name

Environment variable: QUARKUS_OIDC_INTROSPECTION_CREDENTIALS_NAME

Show more

string

Secret

Environment variable: QUARKUS_OIDC_INTROSPECTION_CREDENTIALS_SECRET

Show more

string

Include OpenId Connect Client ID configured with 'quarkus.oidc.client-id'

Environment variable: QUARKUS_OIDC_INTROSPECTION_CREDENTIALS_INCLUDE_CLIENT_ID

Show more

boolean

true

List of paths to claims containing an array of groups. Each path starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: "realm/groups". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in one or more different claims.

Environment variable: QUARKUS_OIDC_ROLES_ROLE_CLAIM_PATH

Show more

文字列のリスト

Separator for splitting a string which may contain multiple group values. It will only be used if the "role-claim-path" property points to one or more custom claims whose values are strings. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence.

Environment variable: QUARKUS_OIDC_ROLES_ROLE_CLAIM_SEPARATOR

Show more

string

Source of the principal roles.

Environment variable: QUARKUS_OIDC_ROLES_SOURCE

Show more

idtokenID Token - the default value for the 'web-app' applications., accesstokenAccess Token - the default value for the 'service' applications; can also be used as the source of roles for the 'web-app' applications., userinfoUser Info

Expected issuer 'iss' claim value. Note this property overrides the issuer property which may be set in OpenId Connect provider’s well-known configuration. If the iss claim value varies depending on the host/IP address or tenant id of the provider then you may skip the issuer verification by setting this property to 'any' but it should be done only when other options (such as configuring the provider to use the fixed iss claim value) are not possible.

Environment variable: QUARKUS_OIDC_TOKEN_ISSUER

Show more

string

Expected audience 'aud' claim value which may be a string or an array of strings.

Environment variable: QUARKUS_OIDC_TOKEN_AUDIENCE

Show more

文字列のリスト

Expected token type

Environment variable: QUARKUS_OIDC_TOKEN_TOKEN_TYPE

Show more

string

Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds.

Environment variable: QUARKUS_OIDC_TOKEN_LIFESPAN_GRACE

Show more

int

Token age. It allows for the number of seconds to be specified that must not elapse since the iat (issued at) time. A small leeway to account for clock skew which can be configured with 'quarkus.oidc.token.lifespan-grace' to verify the token expiry time can also be used to verify the token age property. Note that setting this property does not relax the requirement that Bearer and Code Flow JWT tokens must have a valid ('exp') expiry claim value. The only exception where setting this property relaxes the requirement is when a logout token is sent with a back-channel logout request since the current OpenId Connect Back-Channel specification does not explicitly require the logout tokens to contain an 'exp' claim. However, even if the current logout token is allowed to have no 'exp' claim, the exp claim will be still verified if the logout token contains it.

Environment variable: QUARKUS_OIDC_TOKEN_AGE

Show more

Duration

Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and sub claims are checked.

Environment variable: QUARKUS_OIDC_TOKEN_PRINCIPAL_CLAIM

Show more

string

Refresh expired authorization code flow ID or access tokens. If this property is enabled then a refresh token request will be performed if the authorization code ID or access token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the authentication.session-age-extension property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type ApplicationType#WEB_APP}.

Environment variable: QUARKUS_OIDC_TOKEN_REFRESH_EXPIRED

Show more

boolean

false

Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking if the authorization code ID or access token should be refreshed. If the sum is greater than the authorization code ID or access token’s expiration time then a refresh is going to happen. This property will be ignored if the 'refresh-expired' property is not enabled.

Environment variable: QUARKUS_OIDC_TOKEN_REFRESH_TOKEN_TIME_SKEW

Show more

Duration

Forced JWK set refresh interval in minutes.

Environment variable: QUARKUS_OIDC_TOKEN_FORCED_JWK_REFRESH_INTERVAL

Show more

Duration

10M

Custom HTTP header that contains a bearer token. This option is valid only when the application is of type ApplicationType#SERVICE}.

Environment variable: QUARKUS_OIDC_TOKEN_HEADER

Show more

string

Decryption key location. JWT tokens can be inner-signed and encrypted by OpenId Connect providers. However, it is not always possible to remotely introspect such tokens because the providers may not control the private decryption keys. In such cases set this property to point to the file containing the decryption private key in PEM or JSON Web Key (JWK) format. Note that if a 'private_key_jwt' client authentication method is used then the private key which is used to sign client authentication JWT tokens will be used to try to decrypt an encrypted ID token if this property is not set.

Environment variable: QUARKUS_OIDC_TOKEN_DECRYPTION_KEY_LOCATION

Show more

string

Allow the remote introspection of JWT tokens when no matching JWK key is available. Note this property is set to 'true' by default for backward-compatibility reasons and will be set to false instead in one of the next releases. Also note this property will be ignored if JWK endpoint URI is not available and introspecting the tokens is the only verification option.

Environment variable: QUARKUS_OIDC_TOKEN_ALLOW_JWT_INTROSPECTION

Show more

boolean

true

Require that JWT tokens are only introspected remotely.

Environment variable: QUARKUS_OIDC_TOKEN_REQUIRE_JWT_INTROSPECTION_ONLY

Show more

boolean

false

Allow the remote introspection of the opaque tokens. Set this property to 'false' if only JWT tokens are expected.

Environment variable: QUARKUS_OIDC_TOKEN_ALLOW_OPAQUE_TOKEN_INTROSPECTION

Show more

boolean

true

Indirectly verify that the opaque (binary) access token is valid by using it to request UserInfo. Opaque access token is considered valid if the provider accepted this token and returned a valid UserInfo. You should only enable this option if the opaque access tokens have to be accepted but OpenId Connect provider does not have a token introspection endpoint. This property will have no effect when JWT tokens have to be verified.

Environment variable: QUARKUS_OIDC_TOKEN_VERIFY_ACCESS_TOKEN_WITH_USER_INFO

Show more

boolean

false

The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification.

Environment variable: QUARKUS_OIDC_LOGOUT_PATH

Show more

string

Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI.

Environment variable: QUARKUS_OIDC_LOGOUT_POST_LOGOUT_PATH

Show more

string

Name of the post logout URI parameter which will be added as a query parameter to the logout redirect URI.

Environment variable: QUARKUS_OIDC_LOGOUT_POST_LOGOUT_URI_PARAM

Show more

string

post_logout_redirect_uri

The relative path of the Back-Channel Logout endpoint at the application.

Environment variable: QUARKUS_OIDC_LOGOUT_BACKCHANNEL_PATH

Show more

string

The relative path of the Front-Channel Logout endpoint at the application.

Environment variable: QUARKUS_OIDC_LOGOUT_FRONTCHANNEL_PATH

Show more

string

Authorization code flow response mode

Environment variable: QUARKUS_OIDC_AUTHENTICATION_RESPONSE_MODE

Show more

queryAuthorization response parameters are encoded in the query string added to the redirect_uri, form-postAuthorization response parameters are encoded as HTML form values that are auto-submitted in the browser and transmitted via the HTTP POST method using the application/x-www-form-urlencoded content type

query

Relative path for calculating a "redirect_uri" query parameter. It has to start from a forward slash and will be appended to the request URI’s host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated if 'restorePathAfterRedirect' is set to 'true'.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_REDIRECT_PATH

Show more

string

If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. Note if redirectPath property is not set, the original request URI will be restored even if this property is disabled.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_RESTORE_PATH_AFTER_REDIRECT

Show more

boolean

false

Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_REMOVE_REDIRECT_PARAMETERS

Show more

boolean

true

Relative path to the public endpoint which will process the error response from the OIDC authorization endpoint. If the user authentication has failed then the OIDC provider will return an 'error' and an optional 'error_description' parameters, instead of the expected authorization 'code'. If this property is set then the user will be redirected to the endpoint which can return a user-friendly error description page. It has to start from a forward slash and will be appended to the request URI’s host and port. For example, if it is set as '/error' and the current request URI is 'https://localhost:8080/callback?error=invalid_scope' then a redirect will be made to 'https://localhost:8080/error?error=invalid_scope'. If this property is not set then HTTP 401 status will be returned in case of the user authentication failure.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_ERROR_PATH

Show more

string

Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if quarkus.oidc.roles.source property is set to accesstoken which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_VERIFY_ACCESS_TOKEN

Show more

boolean

false

Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout post_logout_redirect_uri and the local redirect requests.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_FORCE_REDIRECT_HTTPS_SCHEME

Show more

boolean

false

List of scopes

Environment variable: QUARKUS_OIDC_AUTHENTICATION_SCOPES

Show more

文字列のリスト

Add the 'openid' scope automatically to the list of scopes. This is required for OpenId Connect providers but will not work for OAuth2 providers such as Twitter OAuth2 which does not accept that scope and throws an error.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_ADD_OPENID_SCOPE

Show more

boolean

true

Request URL query parameters which, if present, will be added to the authentication redirect URI.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_FORWARD_PARAMS

Show more

文字列のリスト

If enabled the state, session and post logout cookies will have their 'secure' parameter set to 'true' when HTTP is used. It may be necessary when running behind an SSL terminating reverse proxy. The cookies will always be secure if HTTPS is used even if this property is set to false.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_FORCE_SECURE

Show more

boolean

false

Cookie name suffix. For example, a session cookie name for the default OIDC tenant is 'q_session' but can be changed to 'q_session_test' if this property is set to 'test'.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_SUFFIX

Show more

string

Cookie path parameter value which, if set, will be used to set a path parameter for the session, state and post logout cookies. The cookie-path-header property, if set, will be checked first.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_PATH

Show more

string

/

Cookie path header parameter value which, if set, identifies the incoming HTTP header whose value will be used to set a path parameter for the session, state and post logout cookies. If the header is missing then the cookie-path property will be checked.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_PATH_HEADER

Show more

string

Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_DOMAIN

Show more

string

SameSite attribute for the session cookie.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_COOKIE_SAME_SITE

Show more

strict, lax, none

lax

If this property is set to 'true' then an OIDC UserInfo endpoint will be called.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_USER_INFO_REQUIRED

Show more

boolean

false

Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the token.refresh-expired property has not been enabled.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_SESSION_AGE_EXTENSION

Show more

Duration

5M

If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to false then a status code of '499' will be returned to allow the client to handle the redirect manually

Environment variable: QUARKUS_OIDC_AUTHENTICATION_JAVA_SCRIPT_AUTO_REDIRECT

Show more

boolean

true

Requires that ID token is available when the authorization code flow completes. Disable this property only when you need to use the authorization code flow with OAuth2 providers which do not return ID token - an internal IdToken will be generated in such cases.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_ID_TOKEN_REQUIRED

Show more

boolean

true

Internal ID token lifespan. This property is only checked when an internal IdToken is generated when Oauth2 providers do not return IdToken.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_INTERNAL_ID_TOKEN_LIFESPAN

Show more

Duration

5M

Requires that a Proof Key for Code Exchange (PKCE) is used.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_PKCE_REQUIRED

Show more

boolean

false

Secret which will be used to encrypt a Proof Key for Code Exchange (PKCE) code verifier in the code flow state. This secret must be set if PKCE is required but no client secret is set. The length of the secret which will be used to encrypt the code verifier must be 32 characters long.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_PKCE_SECRET

Show more

string

Default TokenStateManager strategy.

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_STRATEGY

Show more

keep-all-tokensKeep ID, access and refresh tokens., id-tokenKeep ID token only, id-refresh-tokensKeep ID and refresh tokens only

keep-all-tokens

Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_SPLIT_TOKENS

Show more

boolean

false

Requires that the tokens are encrypted before being stored in the cookies.

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_ENCRYPTION_REQUIRED

Show more

boolean

false

Secret which will be used to encrypt the tokens. This secret must be set if the token encryption is required but no client secret is set. The length of the secret which will be used to encrypt the tokens must be 32 characters long.

Environment variable: QUARKUS_OIDC_TOKEN_STATE_MANAGER_ENCRYPTION_SECRET

Show more

string

Allow caching the token introspection data. Note enabling this property does not enable the cache itself but only permits to cache the token introspection for a given tenant. If the default token cache can be used then please see OidcConfig.TokenCache how to enable it.

Environment variable: QUARKUS_OIDC_ALLOW_TOKEN_INTROSPECTION_CACHE

Show more

boolean

true

Allow caching the user info data. Note enabling this property does not enable the cache itself but only permits to cache the user info data for a given tenant. If the default token cache can be used then please see OidcConfig.TokenCache how to enable it.

Environment variable: QUARKUS_OIDC_ALLOW_USER_INFO_CACHE

Show more

boolean

true

Allow inlining UserInfo in IdToken instead of caching it in the token cache. This property is only checked when an internal IdToken is generated when Oauth2 providers do not return IdToken. Inlining UserInfo in the generated IdToken allows to store it in the session cookie and avoids introducing a cached state.

Environment variable: QUARKUS_OIDC_CACHE_USER_INFO_IN_IDTOKEN

Show more

boolean

false

Well known OpenId Connect provider identifier

Environment variable: QUARKUS_OIDC_PROVIDER

Show more

apple, facebook, github, google, microsoft, spotify, twitter

Maximum number of cache entries. Set it to a positive value if the cache has to be enabled.

Environment variable: QUARKUS_OIDC_TOKEN_CACHE_MAX_SIZE

Show more

int

0

Maximum amount of time a given cache entry is valid for.

Environment variable: QUARKUS_OIDC_TOKEN_CACHE_TIME_TO_LIVE

Show more

Duration

3M

Clean up timer interval. If this property is set then a timer will check and remove the stale entries periodically.

Environment variable: QUARKUS_OIDC_TOKEN_CACHE_CLEAN_UP_TIMER_INTERVAL

Show more

Duration

Grant options

Environment variable: QUARKUS_OIDC_DEVUI_GRANT_OPTIONS

Show more

Map<String,Map<String,String>>

A map of required claims and their expected values. For example, quarkus.oidc.token.required-claims.org_id = org_xyz would require tokens to have the org_id claim to be present and set to org_xyz. Strings are the only supported types. Use SecurityIdentityAugmentor to verify claims of other types or complex claims.

Environment variable: QUARKUS_OIDC_TOKEN_REQUIRED_CLAIMS

Show more

Map<String,String>

Additional properties which will be added as the query parameters to the logout redirect URI.

Environment variable: QUARKUS_OIDC_LOGOUT_EXTRA_PARAMS

Show more

Map<String,String>

Additional properties which will be added as the query parameters to the authentication redirect URI.

Environment variable: QUARKUS_OIDC_AUTHENTICATION_EXTRA_PARAMS

Show more

Map<String,String>

Additional parameters, in addition to the required code and redirect-uri parameters, which have to be included to complete the authorization code grant request.

Environment variable: QUARKUS_OIDC_CODE_GRANT_EXTRA_PARAMS

Show more

Map<String,String>

Custom HTTP headers which have to be sent to complete the authorization code grant request.

Environment variable: QUARKUS_OIDC_CODE_GRANT_HEADERS

Show more

Map<String,String>

Additional named tenants

タイプ

デフォルト

The base URL of the OpenID Connect (OIDC) server, for example, https://host:port/auth. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: https://host:port/realms/{realm} where {realm} has to be replaced by the name of the Keycloak realm.

Environment variable: QUARKUS_OIDC__TENANT__AUTH_SERVER_URL

Show more

string

Enables OIDC discovery. If the discovery is disabled then the OIDC endpoint URLs must be configured individually.

Environment variable: QUARKUS_OIDC__TENANT__DISCOVERY_ENABLED

Show more

boolean

true

Relative path or absolute URL of the OIDC token endpoint which issues access and refresh tokens.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_PATH

Show more

string

Relative path or absolute URL of the OIDC token revocation endpoint.

Environment variable: QUARKUS_OIDC__TENANT__REVOKE_PATH

Show more

string

The client-id of the application. Each application has a client-id that is used to identify the application

Environment variable: QUARKUS_OIDC__TENANT__CLIENT_ID

Show more

string

The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to 20S will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped.

Environment variable: QUARKUS_OIDC__TENANT__CONNECTION_DELAY

Show more

Duration

The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the connection-delay property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property.

Environment variable: QUARKUS_OIDC__TENANT__CONNECTION_RETRY_COUNT

Show more

int

3

The amount of time after which the current OIDC connection request will time out.

Environment variable: QUARKUS_OIDC__TENANT__CONNECTION_TIMEOUT

Show more

Duration

10S

The maximum size of the connection pool used by the WebClient

Environment variable: QUARKUS_OIDC__TENANT__MAX_POOL_SIZE

Show more

int

Client secret which is used for a client_secret_basic authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive.

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_SECRET

Show more

string

The client secret value - it will be ignored if 'secret.key' is set

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_CLIENT_SECRET_VALUE

Show more

string

The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_CLIENT_SECRET_PROVIDER_NAME

Show more

string

The CredentialsProvider client secret key

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_CLIENT_SECRET_PROVIDER_KEY

Show more

string

Authentication method.

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_CLIENT_SECRET_METHOD

Show more

basicclient_secret_basic (default): client id and secret are submitted with the HTTP Authorization Basic scheme, postclient_secret_post: client id and secret are submitted as the 'client_id' and 'client_secret' form parameters., post-jwtclient_secret_jwt: client id and generated JWT secret are submitted as the 'client_id' and 'client_secret' form parameters.

If provided, indicates that JWT is signed using a secret key

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_SECRET

Show more

string

The CredentialsProvider name which should only be set if more than one CredentialsProvider is registered

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_SECRET_PROVIDER_NAME

Show more

string

The CredentialsProvider client secret key

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_SECRET_PROVIDER_KEY

Show more

string

If provided, indicates that JWT is signed using a private key in PEM or JWK format. You can use the signature-algorithm property to specify the key algorithm.

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_KEY_FILE

Show more

string

If provided, indicates that JWT is signed using a private key from a key store

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_KEY_STORE_FILE

Show more

string

A parameter to specify the password of the key store file. If not given, the default ("password") is used.

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_KEY_STORE_PASSWORD

Show more

string

password

The private key id/alias

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_KEY_ID

Show more

string

The private key password

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_KEY_PASSWORD

Show more

string

password

JWT audience ('aud') claim value. By default, the audience is set to the address of the OpenId Connect Provider’s token endpoint.

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_AUDIENCE

Show more

string

Key identifier of the signing key added as a JWT 'kid' header

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_TOKEN_KEY_ID

Show more

string

Issuer of the signing key added as a JWT 'iss' claim (default: client id)

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_ISSUER

Show more

string

Subject of the signing key added as a JWT 'sub' claim (default: client id)

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_SUBJECT

Show more

string

Signature algorithm, also used for the key-file property. Supported values: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, HS256, HS384, HS512.

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_SIGNATURE_ALGORITHM

Show more

string

JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time.

Environment variable: QUARKUS_OIDC__TENANT__CREDENTIALS_JWT_LIFESPAN

Show more

int

10

The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the "host" config item must be configured to enable the usage of a Proxy.

Environment variable: QUARKUS_OIDC__TENANT__PROXY_HOST

Show more

string

The port number of the Proxy. Default value is 80.

Environment variable: QUARKUS_OIDC__TENANT__PROXY_PORT

Show more

int

80

The username, if Proxy needs authentication.

Environment variable: QUARKUS_OIDC__TENANT__PROXY_USERNAME

Show more

string

The password, if Proxy needs authentication.

Environment variable: QUARKUS_OIDC__TENANT__PROXY_PASSWORD

Show more

string

Certificate validation and hostname verification, which can be one of the following values from enum Verification. Default is required.

Environment variable: QUARKUS_OIDC__TENANT__TLS_VERIFICATION

Show more

requiredCertificates are validated and hostname verification is enabled. This is the default value., certificate-validationCertificates are validated but hostname verification is disabled., noneAll certificated are trusted and hostname verification is disabled.

An optional key store which holds the certificate information instead of specifying separate files.

Environment variable: QUARKUS_OIDC__TENANT__TLS_KEY_STORE_FILE

Show more

path

An optional parameter to specify type of the key store file. If not given, the type is automatically detected based on the file name.

Environment variable: QUARKUS_OIDC__TENANT__TLS_KEY_STORE_FILE_TYPE

Show more

string

An optional parameter to specify a provider of the key store file. If not given, the provider is automatically detected based on the key store file type.

Environment variable: QUARKUS_OIDC__TENANT__TLS_KEY_STORE_PROVIDER

Show more

string

A parameter to specify the password of the key store file. If not given, the default ("password") is used.

Environment variable: QUARKUS_OIDC__TENANT__TLS_KEY_STORE_PASSWORD

Show more

string

password

An optional parameter to select a specific key in the key store. When SNI is disabled, if the key store contains multiple keys and no alias is specified, the behavior is undefined.

Environment variable: QUARKUS_OIDC__TENANT__TLS_KEY_STORE_KEY_ALIAS

Show more

string

An optional parameter to define the password for the key, in case it’s different from key-store-password.

Environment variable: QUARKUS_OIDC__TENANT__TLS_KEY_STORE_KEY_PASSWORD

Show more

string

An optional trust store which holds the certificate information of the certificates to trust

Environment variable: QUARKUS_OIDC__TENANT__TLS_TRUST_STORE_FILE

Show more

path

A parameter to specify the password of the trust store file.

Environment variable: QUARKUS_OIDC__TENANT__TLS_TRUST_STORE_PASSWORD

Show more

string

A parameter to specify the alias of the trust store certificate.

Environment variable: QUARKUS_OIDC__TENANT__TLS_TRUST_STORE_CERT_ALIAS

Show more

string

An optional parameter to specify type of the trust store file. If not given, the type is automatically detected based on the file name.

Environment variable: QUARKUS_OIDC__TENANT__TLS_TRUST_STORE_FILE_TYPE

Show more

string

An optional parameter to specify a provider of the trust store file. If not given, the provider is automatically detected based on the trust store file type.

Environment variable: QUARKUS_OIDC__TENANT__TLS_TRUST_STORE_PROVIDER

Show more

string

A unique tenant identifier. It must be set by TenantConfigResolver providers which resolve the tenant configuration dynamically and is optional in all other cases.

Environment variable: QUARKUS_OIDC__TENANT__TENANT_ID

Show more

string

If this tenant configuration is enabled.

Environment variable: QUARKUS_OIDC__TENANT__TENANT_ENABLED

Show more

boolean

true

The application type, which can be one of the following values from enum ApplicationType.

Environment variable: QUARKUS_OIDC__TENANT__APPLICATION_TYPE

Show more

web-appA WEB_APP is a client that serves pages, usually a frontend application. For this type of client the Authorization Code Flow is defined as the preferred method for authenticating users., serviceA SERVICE is a client that has a set of protected HTTP resources, usually a backend application following the RESTful Architectural Design. For this type of client, the Bearer Authorization method is defined as the preferred method for authenticating and authorizing users., hybridA combined SERVICE and WEB_APP client. For this type of client, the Bearer Authorization method will be used if the Authorization header is set and Authorization Code Flow - if not.

service

Relative path or absolute URL of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC__TENANT__AUTHORIZATION_PATH

Show more

string

Relative path or absolute URL of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC__TENANT__USER_INFO_PATH

Show more

string

Relative path or absolute URL of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC__TENANT__INTROSPECTION_PATH

Show more

string

Relative path or absolute URL of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC__TENANT__JWKS_PATH

Show more

string

Relative path or absolute URL of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled.

Environment variable: QUARKUS_OIDC__TENANT__END_SESSION_PATH

Show more

string

Public key for the local JWT token verification. OIDC server connection will not be created when this property is set.

Environment variable: QUARKUS_OIDC__TENANT__PUBLIC_KEY

Show more

string

Name

Environment variable: QUARKUS_OIDC__TENANT__INTROSPECTION_CREDENTIALS_NAME

Show more

string

Secret

Environment variable: QUARKUS_OIDC__TENANT__INTROSPECTION_CREDENTIALS_SECRET

Show more

string

Include OpenId Connect Client ID configured with 'quarkus.oidc.client-id'

Environment variable: QUARKUS_OIDC__TENANT__INTROSPECTION_CREDENTIALS_INCLUDE_CLIENT_ID

Show more

boolean

true

List of paths to claims containing an array of groups. Each path starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: "realm/groups". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in one or more different claims.

Environment variable: QUARKUS_OIDC__TENANT__ROLES_ROLE_CLAIM_PATH

Show more

文字列のリスト

Separator for splitting a string which may contain multiple group values. It will only be used if the "role-claim-path" property points to one or more custom claims whose values are strings. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence.

Environment variable: QUARKUS_OIDC__TENANT__ROLES_ROLE_CLAIM_SEPARATOR

Show more

string

Source of the principal roles.

Environment variable: QUARKUS_OIDC__TENANT__ROLES_SOURCE

Show more

idtokenID Token - the default value for the 'web-app' applications., accesstokenAccess Token - the default value for the 'service' applications; can also be used as the source of roles for the 'web-app' applications., userinfoUser Info

Expected issuer 'iss' claim value. Note this property overrides the issuer property which may be set in OpenId Connect provider’s well-known configuration. If the iss claim value varies depending on the host/IP address or tenant id of the provider then you may skip the issuer verification by setting this property to 'any' but it should be done only when other options (such as configuring the provider to use the fixed iss claim value) are not possible.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_ISSUER

Show more

string

Expected audience 'aud' claim value which may be a string or an array of strings.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_AUDIENCE

Show more

文字列のリスト

A map of required claims and their expected values. For example, quarkus.oidc.token.required-claims.org_id = org_xyz would require tokens to have the org_id claim to be present and set to org_xyz. Strings are the only supported types. Use SecurityIdentityAugmentor to verify claims of other types or complex claims.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_REQUIRED_CLAIMS

Show more

Map<String,String>

Expected token type

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_TOKEN_TYPE

Show more

string

Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_LIFESPAN_GRACE

Show more

int

Token age. It allows for the number of seconds to be specified that must not elapse since the iat (issued at) time. A small leeway to account for clock skew which can be configured with 'quarkus.oidc.token.lifespan-grace' to verify the token expiry time can also be used to verify the token age property. Note that setting this property does not relax the requirement that Bearer and Code Flow JWT tokens must have a valid ('exp') expiry claim value. The only exception where setting this property relaxes the requirement is when a logout token is sent with a back-channel logout request since the current OpenId Connect Back-Channel specification does not explicitly require the logout tokens to contain an 'exp' claim. However, even if the current logout token is allowed to have no 'exp' claim, the exp claim will be still verified if the logout token contains it.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_AGE

Show more

Duration

Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and sub claims are checked.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_PRINCIPAL_CLAIM

Show more

string

Refresh expired authorization code flow ID or access tokens. If this property is enabled then a refresh token request will be performed if the authorization code ID or access token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the authentication.session-age-extension property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type ApplicationType#WEB_APP}.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_REFRESH_EXPIRED

Show more

boolean

false

Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking if the authorization code ID or access token should be refreshed. If the sum is greater than the authorization code ID or access token’s expiration time then a refresh is going to happen. This property will be ignored if the 'refresh-expired' property is not enabled.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_REFRESH_TOKEN_TIME_SKEW

Show more

Duration

Forced JWK set refresh interval in minutes.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_FORCED_JWK_REFRESH_INTERVAL

Show more

Duration

10M

Custom HTTP header that contains a bearer token. This option is valid only when the application is of type ApplicationType#SERVICE}.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_HEADER

Show more

string

Decryption key location. JWT tokens can be inner-signed and encrypted by OpenId Connect providers. However, it is not always possible to remotely introspect such tokens because the providers may not control the private decryption keys. In such cases set this property to point to the file containing the decryption private key in PEM or JSON Web Key (JWK) format. Note that if a 'private_key_jwt' client authentication method is used then the private key which is used to sign client authentication JWT tokens will be used to try to decrypt an encrypted ID token if this property is not set.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_DECRYPTION_KEY_LOCATION

Show more

string

Allow the remote introspection of JWT tokens when no matching JWK key is available. Note this property is set to 'true' by default for backward-compatibility reasons and will be set to false instead in one of the next releases. Also note this property will be ignored if JWK endpoint URI is not available and introspecting the tokens is the only verification option.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_ALLOW_JWT_INTROSPECTION

Show more

boolean

true

Require that JWT tokens are only introspected remotely.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_REQUIRE_JWT_INTROSPECTION_ONLY

Show more

boolean

false

Allow the remote introspection of the opaque tokens. Set this property to 'false' if only JWT tokens are expected.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_ALLOW_OPAQUE_TOKEN_INTROSPECTION

Show more

boolean

true

Indirectly verify that the opaque (binary) access token is valid by using it to request UserInfo. Opaque access token is considered valid if the provider accepted this token and returned a valid UserInfo. You should only enable this option if the opaque access tokens have to be accepted but OpenId Connect provider does not have a token introspection endpoint. This property will have no effect when JWT tokens have to be verified.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_VERIFY_ACCESS_TOKEN_WITH_USER_INFO

Show more

boolean

false

The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification.

Environment variable: QUARKUS_OIDC__TENANT__LOGOUT_PATH

Show more

string

Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI.

Environment variable: QUARKUS_OIDC__TENANT__LOGOUT_POST_LOGOUT_PATH

Show more

string

Name of the post logout URI parameter which will be added as a query parameter to the logout redirect URI.

Environment variable: QUARKUS_OIDC__TENANT__LOGOUT_POST_LOGOUT_URI_PARAM

Show more

string

post_logout_redirect_uri

Additional properties which will be added as the query parameters to the logout redirect URI.

Environment variable: QUARKUS_OIDC__TENANT__LOGOUT_EXTRA_PARAMS

Show more

Map<String,String>

The relative path of the Back-Channel Logout endpoint at the application.

Environment variable: QUARKUS_OIDC__TENANT__LOGOUT_BACKCHANNEL_PATH

Show more

string

The relative path of the Front-Channel Logout endpoint at the application.

Environment variable: QUARKUS_OIDC__TENANT__LOGOUT_FRONTCHANNEL_PATH

Show more

string

Authorization code flow response mode

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_RESPONSE_MODE

Show more

queryAuthorization response parameters are encoded in the query string added to the redirect_uri, form-postAuthorization response parameters are encoded as HTML form values that are auto-submitted in the browser and transmitted via the HTTP POST method using the application/x-www-form-urlencoded content type

query

Relative path for calculating a "redirect_uri" query parameter. It has to start from a forward slash and will be appended to the request URI’s host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated if 'restorePathAfterRedirect' is set to 'true'.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_REDIRECT_PATH

Show more

string

If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. Note if redirectPath property is not set, the original request URI will be restored even if this property is disabled.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_RESTORE_PATH_AFTER_REDIRECT

Show more

boolean

false

Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_REMOVE_REDIRECT_PARAMETERS

Show more

boolean

true

Relative path to the public endpoint which will process the error response from the OIDC authorization endpoint. If the user authentication has failed then the OIDC provider will return an 'error' and an optional 'error_description' parameters, instead of the expected authorization 'code'. If this property is set then the user will be redirected to the endpoint which can return a user-friendly error description page. It has to start from a forward slash and will be appended to the request URI’s host and port. For example, if it is set as '/error' and the current request URI is 'https://localhost:8080/callback?error=invalid_scope' then a redirect will be made to 'https://localhost:8080/error?error=invalid_scope'. If this property is not set then HTTP 401 status will be returned in case of the user authentication failure.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_ERROR_PATH

Show more

string

Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if quarkus.oidc.roles.source property is set to accesstoken which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_VERIFY_ACCESS_TOKEN

Show more

boolean

false

Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout post_logout_redirect_uri and the local redirect requests.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_FORCE_REDIRECT_HTTPS_SCHEME

Show more

boolean

false

List of scopes

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_SCOPES

Show more

文字列のリスト

Add the 'openid' scope automatically to the list of scopes. This is required for OpenId Connect providers but will not work for OAuth2 providers such as Twitter OAuth2 which does not accept that scope and throws an error.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_ADD_OPENID_SCOPE

Show more

boolean

true

Additional properties which will be added as the query parameters to the authentication redirect URI.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_EXTRA_PARAMS

Show more

Map<String,String>

Request URL query parameters which, if present, will be added to the authentication redirect URI.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_FORWARD_PARAMS

Show more

文字列のリスト

If enabled the state, session and post logout cookies will have their 'secure' parameter set to 'true' when HTTP is used. It may be necessary when running behind an SSL terminating reverse proxy. The cookies will always be secure if HTTPS is used even if this property is set to false.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_COOKIE_FORCE_SECURE

Show more

boolean

false

Cookie name suffix. For example, a session cookie name for the default OIDC tenant is 'q_session' but can be changed to 'q_session_test' if this property is set to 'test'.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_COOKIE_SUFFIX

Show more

string

Cookie path parameter value which, if set, will be used to set a path parameter for the session, state and post logout cookies. The cookie-path-header property, if set, will be checked first.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_COOKIE_PATH

Show more

string

/

Cookie path header parameter value which, if set, identifies the incoming HTTP header whose value will be used to set a path parameter for the session, state and post logout cookies. If the header is missing then the cookie-path property will be checked.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_COOKIE_PATH_HEADER

Show more

string

Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_COOKIE_DOMAIN

Show more

string

SameSite attribute for the session cookie.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_COOKIE_SAME_SITE

Show more

strict, lax, none

lax

If this property is set to 'true' then an OIDC UserInfo endpoint will be called.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_USER_INFO_REQUIRED

Show more

boolean

false

Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the token.refresh-expired property has not been enabled.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_SESSION_AGE_EXTENSION

Show more

Duration

5M

If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to false then a status code of '499' will be returned to allow the client to handle the redirect manually

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_JAVA_SCRIPT_AUTO_REDIRECT

Show more

boolean

true

Requires that ID token is available when the authorization code flow completes. Disable this property only when you need to use the authorization code flow with OAuth2 providers which do not return ID token - an internal IdToken will be generated in such cases.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_ID_TOKEN_REQUIRED

Show more

boolean

true

Internal ID token lifespan. This property is only checked when an internal IdToken is generated when Oauth2 providers do not return IdToken.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_INTERNAL_ID_TOKEN_LIFESPAN

Show more

Duration

5M

Requires that a Proof Key for Code Exchange (PKCE) is used.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_PKCE_REQUIRED

Show more

boolean

false

Secret which will be used to encrypt a Proof Key for Code Exchange (PKCE) code verifier in the code flow state. This secret must be set if PKCE is required but no client secret is set. The length of the secret which will be used to encrypt the code verifier must be 32 characters long.

Environment variable: QUARKUS_OIDC__TENANT__AUTHENTICATION_PKCE_SECRET

Show more

string

Additional parameters, in addition to the required code and redirect-uri parameters, which have to be included to complete the authorization code grant request.

Environment variable: QUARKUS_OIDC__TENANT__CODE_GRANT_EXTRA_PARAMS

Show more

Map<String,String>

Custom HTTP headers which have to be sent to complete the authorization code grant request.

Environment variable: QUARKUS_OIDC__TENANT__CODE_GRANT_HEADERS

Show more

Map<String,String>

Default TokenStateManager strategy.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_STATE_MANAGER_STRATEGY

Show more

keep-all-tokensKeep ID, access and refresh tokens., id-tokenKeep ID token only, id-refresh-tokensKeep ID and refresh tokens only

keep-all-tokens

Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_STATE_MANAGER_SPLIT_TOKENS

Show more

boolean

false

Requires that the tokens are encrypted before being stored in the cookies.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_STATE_MANAGER_ENCRYPTION_REQUIRED

Show more

boolean

false

Secret which will be used to encrypt the tokens. This secret must be set if the token encryption is required but no client secret is set. The length of the secret which will be used to encrypt the tokens must be 32 characters long.

Environment variable: QUARKUS_OIDC__TENANT__TOKEN_STATE_MANAGER_ENCRYPTION_SECRET

Show more

string

Allow caching the token introspection data. Note enabling this property does not enable the cache itself but only permits to cache the token introspection for a given tenant. If the default token cache can be used then please see OidcConfig.TokenCache how to enable it.

Environment variable: QUARKUS_OIDC__TENANT__ALLOW_TOKEN_INTROSPECTION_CACHE

Show more

boolean

true

Allow caching the user info data. Note enabling this property does not enable the cache itself but only permits to cache the user info data for a given tenant. If the default token cache can be used then please see OidcConfig.TokenCache how to enable it.

Environment variable: QUARKUS_OIDC__TENANT__ALLOW_USER_INFO_CACHE

Show more

boolean

true

Allow inlining UserInfo in IdToken instead of caching it in the token cache. This property is only checked when an internal IdToken is generated when Oauth2 providers do not return IdToken. Inlining UserInfo in the generated IdToken allows to store it in the session cookie and avoids introducing a cached state.

Environment variable: QUARKUS_OIDC__TENANT__CACHE_USER_INFO_IN_IDTOKEN

Show more

boolean

false

Well known OpenId Connect provider identifier

Environment variable: QUARKUS_OIDC__TENANT__PROVIDER

Show more

apple, facebook, github, google, microsoft, spotify, twitter

期間フォーマットについて

期間のフォーマットは標準の java.time.Duration フォーマットを使用します。詳細は Duration#parse() javadoc を参照してください。

数値で始まる期間の値を指定することもできます。この場合、値が数値のみで構成されている場合、コンバーターは値を秒として扱います。そうでない場合は、 PT が暗黙的に値の前に付加され、標準の java.time.Duration 形式が得られます。

設定例:

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=backend-service
quarkus.oidc.credentials.secret=secret

# Tell Dev Services for Keycloak to import the realm file
# This property is not effective when running the application in JVM or Native modes

quarkus.keycloak.devservices.realm-path=quarkus-realm.json
quarkus.oidc.auth-server-url%prod. プロファイルのプレフィックスを追加すると、アプリケーションが開発モードで実行されたときに Dev Services for Keycloak がコンテナを起動するようになります。詳しくは、後述の 開発モードでのアプリケーションの実行 をご覧ください。

Keycloak サーバーの起動と設定

アプリケーションを開発モードで実行しているときは、Keycloak サーバーを起動しないでください。 Dev Services for Keycloak はコンテナーを起動します。詳細については、以下の Running the Application in Dev mode セクションを参照してください。 レルム設定ファイル をクラスパス (target/classes ディレクトリー) に配置して、開発モードで実行しているときに自動的にインポートされるようにします (すでに 完全なソリューション をビルドしている場合を除く (このレルムファイルはビルド時にクラスパスに追加されます))。

Keycloak サーバーを起動するにはDockerを使用し、以下のコマンドを実行するだけです。

docker run --name keycloak -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin -p 8180:8080 quay.io/keycloak/keycloak:{keycloak.version} start-dev

ここで、 keycloak.version17.0.0 以上に設定する必要があります。

localhost:8180 で Keycloak サーバーにアクセスできるはずです。

Keycloak 管理コンソールにアクセスするには、 admin ユーザーとしてログインしてください。ユーザー名は admin 、パスワードは admin です。

新しいレルムを作成するには、https://github.com/quarkusio/quarkus-quickstarts/tree/2.16/security-openid-connect-quickstart/config/quarkus-realm.json[realm設定ファイル]をインポートします。 新しいレルムを作成する 方法について詳しくはKeycloakのドキュメントを参照してください。

Keycloak Admin Clientを使用して、アプリケーションからサーバーを設定したい場合は、 quarkus-keycloak-admin-client エクステンションまたは quarkus-keycloak-admin-client-reactive エクステンション (アプリケーションが quarkus-rest-client-reactive を使用する場合) のどちらかを含める必要があります。詳しくは Quarkus Keycloak Admin Client ガイドをご覧ください。

開発モードでのアプリケーションの実行

アプリケーションを開発モードで実行するには、次を使用します。

コマンドラインインタフェース
quarkus dev
Maven
./mvnw quarkus:dev
Gradle
./gradlew --console=plain quarkusDev

Dev Services for Keycloak は、Keycloak コンテナーを起動し、 quarkus-realm.json をインポートします。

/q/dev で入手可能な Dev UI を開き、 OpenID Connect Dev UIProvider: Keycloak リンクをクリックします。

OpenID Connect Dev UI が提供する Single Page Application へのログインを求められます。

  • user のロールを持つ alice (パスワード: alice) としてログインします

    • /api/admin にアクセスすると、 403 が返されます

    • /api/users/me にアクセスすると、 200 が返されます

  • ログアウトし、 adminuser ロールの両方を持つ admin (パスワード: admin) としててログインします

    • /api/admin にアクセスすると、 200 が返されます

    • /api/users/me にアクセスすると、 200 が返されます

JVM モードでのアプリケーションの実行

dev モード」で遊び終わったら、標準のJavaアプリケーションとして実行することができます。

まずコンパイルします。

コマンドラインインタフェース
quarkus build
Maven
./mvnw install
Gradle
./gradlew build

次に、以下を実行してください。

java -jar target/quarkus-app/quarkus-run.jar

ネイティブモードでのアプリケーションの実行

同じデモをネイティブコードにコンパイルすることができます。

これは、生成されたバイナリーにランタイム技術が含まれており、最小限のリソースオーバーヘッドで実行できるように最適化されているため、本番環境にJVMをインストールする必要がないことを意味します。

コンパイルには少し時間がかかるので、このステップはデフォルトで無効になっています。 native プロファイルを有効にして再度ビルドしてみましょう。

コマンドラインインタフェース
quarkus build --native
Maven
./mvnw install -Dnative
Gradle
./gradlew build -Dquarkus.package.type=native

コーヒーを飲み終わると、このバイナリーは以下のように直接実行出来るようになります:

./target/security-openid-connect-quickstart-1.0.0-SNAPSHOT-runner

アプリケーションのテスト

開発モードでのアプリケーションのテストについては、上記の 開発モードでのアプリケーションの実行 セクションを参照してください。

curl を使用して、JVM またはネイティブモードで起動したアプリケーションをテストできます。

アプリケーションはベアラートークン認可を使用しており、まず最初に行うべきことは、アプリケーションのリソースにアクセスするためにKeycloak サーバーからアクセストークンを取得することです。

export access_token=$(\
    curl --insecure -X POST http://localhost:8180/realms/quarkus/protocol/openid-connect/token \
    --user backend-service:secret \
    -H 'content-type: application/x-www-form-urlencoded' \
    -d 'username=alice&password=alice&grant_type=password' | jq --raw-output '.access_token' \
 )

上記の例では、ユーザー alice のアクセストークンを取得しています。

どのユーザーでも http://localhost:8080/api/users/me エンドポイントで、基本的にはユーザーに関する詳細な情報を含む JSON ペイロードを返します。

curl -v -X GET \
  http://localhost:8080/api/users/me \
  -H "Authorization: Bearer "$access_token

http://localhost:8080/api/admin エンドポイントは、 admin ロールを持つユーザーのみがアクセスできます。以前に発行されたアクセストークンを使用してこのエンドポイントにアクセスしようとすると、サーバーから 403 応答が返ってくるはずです。

curl -v -X GET \
   http://localhost:8080/api/admin \
   -H "Authorization: Bearer "$access_token

admin エンドポイントにアクセスするには、 admin ユーザーのトークンを取得する必要があります。

export access_token=$(\
    curl --insecure -X POST http://localhost:8180/realms/quarkus/protocol/openid-connect/token \
    --user backend-service:secret \
    -H 'content-type: application/x-www-form-urlencoded' \
    -d 'username=admin&password=admin&grant_type=password' | jq --raw-output '.access_token' \
 )

また、 Dev Services for Keycloak に依存する統合テストの書き方については、以下の Dev Services for Keycloak セクションを参照してください。

リファレンスガイド

JWT クレームへのアクセス

JWT トークンクレームにアクセスする必要がある場合は、 JsonWebToken を注入できます。

package org.acme.security.openid.connect;

import org.eclipse.microprofile.jwt.JsonWebToken;
import javax.inject.Inject;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

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

    @Inject
    JsonWebToken jwt;

    @GET
    @RolesAllowed("admin")
    @Produces(MediaType.TEXT_PLAIN)
    public String admin() {
        return "Access for subject " + jwt.getSubject() + " is granted";
    }
}

JsonWebToken の注入は、 @ApplicationScoped@Singleton、および @RequestScoped スコープでサポートされていますが、個々のクレームがシンプル型として注入される場合は、 @RequestScoped の使用が必要です。 JsonWebToken およびクレームの注入スコープのサポート を参照してください。

ユーザー情報

OIDC userinfo エンドポイントから UserInfo JSON オブジェクトを要求する必要がある場合は quarkus.oidc.authentication.user-info-required=true を設定します。リクエストが OpenId Provider UserInfo エンドポイントに送信され、 io.quarkus.oidc.UserInfo (単純な javax.json.JsonObject ラッパー) オブジェクトが作成されます。 io.quarkus.oidc.UserInfo は、SecurityIdentity userinfo 属性として注入、アクセスすることもできます。

設定メタデータ

現在のテナントが検出した OpenID Connect 設定メタデータio.quarkus.oidc.OidcConfigurationMetadata で表され、 SecurityIdentity configuration-metadata 属性として注入またはアクセスが可能です。

エンドポイントがパブリックの場合、デフォルトのテナントの OidcConfigurationMetadata が注入されます。

トークンクレームとセキュリティーアイデンティティロール

SecurityIdentity ロールは、検証済みの JWT アクセストークンから以下のようにマッピングすることができます。

  • quarkus.oidc.roles.role-claim-path プロパティーが設定されており、一致する配列または文字列のクレームが見つかった場合、このクレームからロールが抽出されます。例えば、 customrolescustomroles/arrayscope"http://namespace-qualified-custom-claim"/roles"http://namespace-qualified-roles" などです。

  • groups クレームが利用可能な場合は、その値が使用されます。

  • realm_access/roles または resource_access/client_id/roles (ここで client_idquarkus.oidc.client-id プロパティーの値)クレームが利用可能な場合は、その値が使用されます。このチェックは、Keycloakが発行するトークンをサポートします。

トークンが不透明(バイナリー)の場合は、リモートトークンイントロスペクションレスポンスの scope プロパティーが使用されます。

UserInfoがロールのソースである場合は、 quarkus.oidc.authentication.user-info-required=truequarkus.oidc.roles.source=userinfo 、必要に応じて quarkus.oidc.roles.role-claim-path を設定します。

さらに、ここ に文書化されているようにロールを追加することにカスタム SecurityIdentityAugmentor を使用することも出来ます。

トークンの検証とイントロスペクション

トークンが JWT トークンの場合、デフォルトでは、OpenID Connect プロバイダーの JWK エンドポイントから取得したローカルの JsonWebKeySet からの JsonWebKey (JWK) キーで検証されます。トークンのキー識別子 kid ヘッダー値は、一致する JWK キーを見つけるために使用されます。一致する JWK がローカルで利用できない場合、 JsonWebKeySet は、JWK エンドポイントから現在のキーセットを取得することによって更新されます。 JsonWebKeySet の更新は、 quarkus.oidc.token.forced-jwk-refresh-interval (デフォルトは 10 分) の期限が切れた後にのみ繰り返すことができます。更新後に一致する JWK が利用できない場合、JWT トークンは OpenID Connectプロバイダーのトークンイントロスペクションエンドポイントに送信されます。

トークンが不透明な場合 (バイナリートークンまたは暗号化された JWT トークンの場合があります)、常に OpenID Connectプロバイダーのトークンイントロスペクションエンドポイントに送信されます。

JWT トークンのみを使用していて、一致する JsonWebKey が常に使用可能になると予想される場合 (おそらくキーセットの更新後)、トークンのイントロスペクションを無効にする必要があります。

quarkus.oidc.token.allow-jwt-introspection=false
quarkus.oidc.token.allow-opaque-token-introspection=false

ただし、JWT トークンをイントロスペクションのみで検証する必要がある場合があります。イントロスペクションエンドポイントアドレスのみを設定することで強制できます。たとえば、Keycloak の場合は、次のように設定できます。

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.discovery-enabled=false
# Token Introspection endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/tokens/introspect
quarkus.oidc.introspection-path=/protocol/openid-connect/tokens/introspect

JWTトークンがリモートでイントロスペクションされるだけのこの間接的な実施方法の利点は、2つのリモートコールが避けられることです。リモートOIDCメタデータディスカバリー呼出と、続く使用されない検証キーを取得する別のリモートコールを避けることが出来ます。一方欠点として、ユーザーがイントロスペクションエンドポイントアドレスを知って、それを手動で構成する必要があることです。

別のアプローチは、OIDCメタデータのディスカバリーは許可するが(これはデフォルトのオプション)、リモートJWTイントロスペクションのみが実行されることを要求することです:

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.token.require-jwt-introspection-only=true

この方法の利点は、設定がシンプルでわかりやすいことですが、欠点は、イントロスペクションのエンドポイントアドレスを発見するために、リモートOIDCメタデータディスカバリー呼び出しが必要なことです(検証キーもフェッチされない)。

io.quarkus.oidc.TokenIntrospection (シンプルな javax.json.JsonObject ラッパー) オブジェクトが作成され、JWT または不透明トークンどちらかのイントロスペクションが成功した場合に SecurityIdentity introspection 属性として注入またはアクセスできることに注意してください。

トークンイントロスペクションと UserInfo キャッシュ

すべての不透明な、場合によっては JWT Bearer アクセストークンは、リモートで検査する必要があります。 UserInfo も必要な場合は、同じアクセストークンを使用して OpenID Connectプロバイダーへのリモート呼び出しを再度実行します。したがって、 UserInfo が必要で、現在のアクセストークンが不透明な場合、そのようなトークンごとに 2 つのリモート呼び出しが行われます。1 つはそれを検査し、もう 1 つは UserInfo を取得します。トークンが JWT の場合、通常は UserInfo を取得するには、1 回のリモート呼び出しだけが必要になります。

着信ベアラーまたはコードフローアクセストークンごとに最大 2 つのリモート呼び出しを行うコストが、問題になる場合があります。

本番環境でこれに当てはまる場合は、トークンのイントロスペクションと UserInfo データを短時間、たとえば 3 - 5 分間キャッシュすることをお勧めします。

quarkus-oidcquarkus.oidc.TokenIntrospectionCachequarkus.oidc.UserInfoCache インターフェイスを提供します。これらは @ApplicationScoped キャッシュ実装を実装するために使用できます。これらは quarkus.oidc.TokenIntrospectionquarkus.oidc.UserInfo オブジェクトを取得および保存するのに使用できます。以下に例を示します。

@ApplicationScoped
@AlternativePriority(1)
public class CustomIntrospectionUserInfoCache implements TokenIntrospectionCache, UserInfoCache {
...
}

各 OIDC テナントは、ブール値 quarkus.oidc."tenant".allow-token-introspection-cache および quarkus.oidc."tenant".allow-user-info-cache プロパティーを使用して、その quarkus.oidc.TokenIntrospectionquarkus.oidc.UserInfo データを保存することを許可または拒否できます。

さらに、 quarkus-oidc は、 quarkus.oidc.TokenIntrospectionCache および quarkus.oidc.UserInfoCache インターフェイスの両方を実装するシンプルなデフォルトのメモリーベースのトークンキャッシュを提供します。

これは、次のようにアクティブ化および設定できます。

# 'max-size' is 0 by default so the cache can be activated by setting 'max-size' to a positive value.
quarkus.oidc.token-cache.max-size=1000
# 'time-to-live' specifies how long a cache entry can be valid for and will be used by a cleanup timer.
quarkus.oidc.token-cache.time-to-live=3M
# 'clean-up-timer-interval' is not set by default so the cleanup timer can be activated by setting 'clean-up-timer-interval'.
quarkus.oidc.token-cache.clean-up-timer-interval=1M

デフォルトのキャッシュはトークンをキーとして使用し、各エントリーは TokenIntrospectionUserInfo を持つことができます。 max-size のエントリー数までしか保持しません。新しいエントリーを追加するときにキャッシュがいっぱいな場合、期限切れのエントリーを 1 つ削除して、スペースを見つけようとします。さらに、クリーンアップタイマーがアクティブになっている場合は、期限切れのエントリーを定期的にチェックして削除します。

デフォルトのキャッシュ実装を試すか、カスタム実装を登録してください。

JSON Web トークンのクレーム検証

ベアラのJWTトークンの署名が検証され、 expires at ( exp) のクレームが確認されると、次に iss ( issuer) クレーム値が検証されます。

デフォルトでは、 iss クレーム値は、well-knownプロバイダの設定で発見された issuer プロパティと比較されます。しかし、 quarkus.oidc.token.issuer プロパティが設定されている場合は、代わりに iss クレーム値がそれと比較されます。

場合によっては、この iss クレームの検証がうまくいかないことがあります。例えば、発見された issuer プロパティに内部の HTTP/IP アドレスが含まれている一方で、トークン iss クレーム値に外部の HTTP/IP アドレスが含まれている場合です。あるいは、発見された issuer プロパティにテンプレートのテナント変数が含まれているが、トークン iss クレーム値には完全なテナント固有の発行者の値が含まれている場合です。

このような場合には、 quarkus.oidc.token.issuer=any を設定して、issuer検証を省略することを検討してください。なお、この設定は推奨されておらず、他に選択肢がない場合を除き、避けるべきです。

  • Keycloakを使用していて、ホストアドレスが異なるために発行者検証エラーが発生する場合は、Keycloakに KEYCLOAK_FRONTEND_URL プロパティを設定して、同じホストアドレスが使用されるようにしてください。

  • マルチテナント展開で iss プロパティがテナント固有のものである場合は、 SecurityIdentity tenant-id 属性を使用して、エンドポイント自体やカスタム JAX-RS フィルタなどでissuerが正しいかどうかを確認することができます。

import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;

import org.eclipse.microprofile.jwt.JsonWebToken;
import io.quarkus.oidc.OidcConfigurationMetadata;
import io.quarkus.security.identity.SecurityIdentity;

@Provider
public class IssuerValidator implements ContainerRequestFilter {
    @Inject
    OidcConfigurationMetadata configMetadata;

    @Inject JsonWebToken jwt;
    @Inject SecurityIdentity identity;

    public void filter(ContainerRequestContext requestContext) {
        String issuer = configMetadata.getIssuer().replace("{tenant-id}", identity.getAttribute("tenant-id"));
        if (!issuer.equals(jwt.getIssuer())) {
            requestContext.abortWith(Response.status(401).build());
        }
    }
}

なお、トークン aud ( audience) のクレーム値を検証するために quarkus.oidc.token.audience プロパティを使用することも推奨します。

シングルページアプリケーション

シングルページアプリケーション (SPA) は通常、 XMLHttpRequest (XHR) と OpenID Connect プロバイダーが提供する JavaScript ユーティリティーコードを使用してBearer Tokenを取得し、それを使用してQuarkus service アプリケーションにアクセスします。

例えば、 keycloak.js を使用してユーザーを認証し、SPA から期限切れのトークンをリフレッシュする方法は以下の通りです。

<html>
<head>
    <title>keycloak-spa</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="http://localhost:8180/js/keycloak.js"></script>
    <script>
        var keycloak = new Keycloak();
        keycloak.init({onLoad: 'login-required'}).success(function () {
            console.log('User is now authenticated.');
        }).error(function () {
            window.location.reload();
        });
        function makeAjaxRequest() {
            axios.get("/api/hello", {
                headers: {
                    'Authorization': 'Bearer ' + keycloak.token
                }
            })
            .then( function (response) {
                console.log("Response: ", response.status);
            }).catch(function (error) {
                console.log('refreshing');
                keycloak.updateToken(5).then(function () {
                    console.log('Token refreshed');
                }).catch(function () {
                    console.log('Failed to refresh token');
                    window.location.reload();
                });
            });
    }
    </script>
</head>
<body>
    <button onclick="makeAjaxRequest()">Request</button>
</body>
</html>

クロスオリジンリソース共有

別のドメインで動作する Single Page Application から OpenID Connect service アプリケーションを利用する場合は、CORS (Cross-Origin Resource Sharing) を設定する必要があります。詳細については、 HTTP CORSのドキュメントを参照してください。

プロバイダーエンドポイント設定

OIDC service アプリケーションは、OpenID Connect プロバイダのトークン、 JsonWebKey (JWK) セット、そして時には UserInfo とイントロスペクションのエンドポイントアドレスを知る必要があります。

デフォルトでは、設定された quarkus.oidc.auth-server-url/.well-known/openid-configuration パスを追加することで検出されます。

また、ディスカバリーエンドポイントが利用できない場合や、ディスカバリーエンドポイントのラウンドトリップを節約したい場合は、ディスカバリーを無効にして、相対パスの値で設定することができます。

quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.discovery-enabled=false
# Token endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/token
quarkus.oidc.token-path=/protocol/openid-connect/token
# JWK set endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/certs
quarkus.oidc.jwks-path=/protocol/openid-connect/certs
# UserInfo endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/userinfo
quarkus.oidc.user-info-path=/protocol/openid-connect/userinfo
# Token Introspection endpoint: http://localhost:8180/realms/quarkus/protocol/openid-connect/tokens/introspect
quarkus.oidc.introspection-path=/protocol/openid-connect/tokens/introspect

トークンの伝播

下流サービスへのベアラアクセストークンの伝播については、トークン伝播 の項を参照してください。

Oidc プロバイダークライアント認証

quarkus.oidc.runtime.OidcProviderClient は、OpenID Connect プロバイダーへのリモートリクエストを実行する必要がある場合に使用されます。Bearer Tokenを検査する必要がある場合は、 OidcProviderClient が OpenID Connect プロバイダーに対して認証する必要があります。サポートされているすべての認証オプションの詳細については、Oidc Provider Client Authentication を参照してください。

テスト

テストプロジェクトに以下の依存関係を追加することから始めます。

pom.xml
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-junit5</artifactId>
    <scope>test</scope>
</dependency>
build.gradle
testImplementation("io.rest-assured:rest-assured")
testImplementation("io.quarkus:quarkus-junit5")

Wiremock

テストプロジェクトに以下の依存関係を追加します。

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-test-oidc-server</artifactId>
    <scope>test</scope>
</dependency>
build.gradle
testImplementation("io.quarkus:quarkus-test-oidc-server")

RESTテストエンドポイントを用意し、例えば以下のように application.properties を設定します。

# keycloak.url is set by OidcWiremockTestResource
quarkus.oidc.auth-server-url=${keycloak.url}/realms/quarkus/
quarkus.oidc.client-id=quarkus-service-app
quarkus.oidc.application-type=service

最後に、例えば次のようにテストコードを書きます。

import static org.hamcrest.Matchers.equalTo;

import java.util.Set;

import org.junit.jupiter.api.Test;

import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.oidc.server.OidcWiremockTestResource;
import io.restassured.RestAssured;
import io.smallrye.jwt.build.Jwt;

@QuarkusTest
@QuarkusTestResource(OidcWiremockTestResource.class)
public class BearerTokenAuthorizationTest {

    @Test
    public void testBearerToken() {
        RestAssured.given().auth().oauth2(getAccessToken("alice", Set.of("user")))
            .when().get("/api/users/me")
            .then()
            .statusCode(200)
            // the test endpoint returns the name extracted from the injected SecurityIdentity Principal
            .body("userName", equalTo("alice"));
    }

    private String getAccessToken(String userName, Set<String> groups) {
        return Jwt.preferredUserName(userName)
                .groups(groups)
                .issuer("https://server.example.com")
                .audience("https://service.example.com")
                .sign();
    }
}

quarkus-test-oidc-server エクステンションには、 JSON Web Key (JWK) 形式の署名 RSA 秘密鍵ファイルが含まれており、 smallrye.jwt.sign.key.location 設定プロパティーでそれをポイントすることに注意してください。引数なしの sign () 操作を使用してトークンに署名できます。

quarkus-oidc service アプリケーションを OidcWiremockTestResource でテストすると、通信チャネルが Wiremock HTTP スタブに対してテストされるため、最高のカバレッジが得られます。 OidcWiremockTestResource は、より複雑な Bearer トークンのテストシナリオをサポートするために、今後強化される予定です。

現在 OidcWiremockTestResource でサポートされていない Wiremock スタブを定義するテストがすぐに必要な場合は、テストクラスに注入された WireMockServer インスタンスを介して行うことができます。次に例を示します。

Wiremock サーバーはテストを実行している JVM で実行されており、Quarkus アプリケーションを実行している Docker コンテナーからはアクセスできないため、 OidcWiremockTestResource は Docker コンテナーに対して @QuarkusIntegrationTest では機能しません。

package io.quarkus.it.keycloak;

import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static org.hamcrest.Matchers.equalTo;

import org.junit.jupiter.api.Test;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;

import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.oidc.server.OidcWireMock;
import io.restassured.RestAssured;

@QuarkusTest
public class CustomOidcWireMockStubTest {

    @OidcWireMock
    WireMockServer wireMockServer;

    @Test
    public void testInvalidBearerToken() {
        wireMockServer.stubFor(WireMock.post("/auth/realms/quarkus/protocol/openid-connect/token/introspect")
                .withRequestBody(matching(".*token=invalid_token.*"))
                .willReturn(WireMock.aResponse().withStatus(400)));

        RestAssured.given().auth().oauth2("invalid_token").when()
                .get("/api/users/me/bearer")
                .then()
                .statusCode(401)
                .header("WWW-Authenticate", equalTo("Bearer"));
    }
}

Dev Services for Keycloak

Keycloak に対する統合テストには、Dev Services for Keycloak を使用することをお勧めします。 Dev Services for Keycloak は、テストコンテナーを起動して初期化します。これにより、 quarkus レルム、 quarkus-app クライアント (secret シークレット) が作成され、 alice (admin および user ロール) および bob (user ロール) ユーザーが追加されます。これらのプロパティーはすべてカスタマイズできます。

まず、次の依存関係を追加する必要があります。

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-test-keycloak-server</artifactId>
    <scope>test</scope>
</dependency>
build.gradle
testImplementation("io.quarkus:quarkus-test-keycloak-server")

これは、アクセストークンを取得するためのテストで使用できるユーティリティークラス io.quarkus.test.keycloak.client.KeycloakTestClient を提供します。

次に、 application.properties を準備します。完全に空の application.properties から始めることができます。これは、 Dev Services for Keycloak が実行中のテストコンテナーをポイントする quarkus.oidc.auth-server-url ならびに quarkus.oidc.client-id=quarkus-app および quarkus.oidc.credentials.secret=secret を登録するためです。

ただし、必要なすべての quarkus-oidc プロパティーがすでに設定されている場合は、 quarkus.oidc.auth-server-urlDev Services for Keycloakprod プロファイルに関連付けるだけでコンテナーを起動できます。以下に例を示します。

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus

テストを実行する前にカスタムレルムファイルを Keycloak にインポートする必要がある場合は、次のように Dev Services for Keycloak を設定できます。

%prod.quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.keycloak.devservices.realm-path=quarkus-realm.json

最後に、JVM モードで実行されるテストを作成します。

package org.acme.security.openid.connect;

import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.keycloak.client.KeycloakTestClient;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;

@QuarkusTest
public class BearerTokenAuthenticationTest {

    KeycloakTestClient keycloakClient = new KeycloakTestClient();

    @Test
    public void testAdminAccess() {
        RestAssured.given().auth().oauth2(getAccessToken("alice"))
                .when().get("/api/admin")
                .then()
                .statusCode(200);
        RestAssured.given().auth().oauth2(getAccessToken("bob"))
                .when().get("/api/admin")
                .then()
                .statusCode(403);
    }

    protected String getAccessToken(String userName) {
        return keycloakClient.getAccessToken(userName);
    }
}

および、ネイティブモードで以下を実行します。

package org.acme.security.openid.connect;

import io.quarkus.test.junit.QuarkusIntegrationTest;

@QuarkusIntegrationTest
public class NativeBearerTokenAuthenticationIT extends BearerTokenAuthenticationTest {
}

初期化および設定方法の詳細については、Dev Services for Keycloak を参照してください。

KeycloakTestResourceLifecycleManager

Keycloak に対して統合テストを行う必要がある場合は、Dev Services For Keycloak で行うことをお勧めします。 Dev Services for Keycloak を使用しない正当な理由がある場合にのみ、テストに KeycloakTestResourceLifecycleManager を使用してください。

以下の依存関係を追加することから始めます。

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-test-keycloak-server</artifactId>
    <scope>test</scope>
</dependency>
build.gradle
testImplementation("io.quarkus:quarkus-test-keycloak-server")

これは、Keycloak コンテナーを開始する io.quarkus.test.common.QuarkusTestResourceLifecycleManager の実装である io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager を提供します。

そして、Maven Surefire プラグインを次のように設定します。

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <!-- or, alternatively, configure 'keycloak.version' -->
            <keycloak.docker.image>${keycloak.docker.image}</keycloak.docker.image>
            <!--
              Disable HTTPS if required:
              <keycloak.use.https>false</keycloak.use.https>
            -->
        </systemPropertyVariables>
    </configuration>
</plugin>

(同様に、ネイティブイメージでテストする場合は maven.failsafe.plugin)。

RESTテストエンドポイントを用意し、例えば以下のように application.properties を設定します。

# keycloak.url is set by KeycloakTestResourceLifecycleManager
quarkus.oidc.auth-server-url=${keycloak.url}/realms/quarkus/
quarkus.oidc.client-id=quarkus-service-app
quarkus.oidc.credentials=secret
quarkus.oidc.application-type=service

最後に、例えば次のようにテストコードを書きます。

import static io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager.getAccessToken;
import static org.hamcrest.Matchers.equalTo;

import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;

import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager;
import io.restassured.RestAssured;

@QuarkusTest
@QuarkusTestResource(KeycloakTestResourceLifecycleManager.class)
public class BearerTokenAuthorizationTest {

    @Test
    public void testBearerToken() {
        RestAssured.given().auth().oauth2(getAccessToken("alice"))))
            .when().get("/api/users/preferredUserName")
            .then()
            .statusCode(200)
            // the test endpoint returns the name extracted from the injected SecurityIdentity Principal
            .body("userName", equalTo("alice"));
    }

}

KeycloakTestResourceLifecycleManageraliceadmin ユーザーを登録します。ユーザー alice にはデフォルトで user ロールしかありませんが、 keycloak.token.user-roles システムプロパティーでカスタマイズできます。ユーザー admin にはデフォルトで useradmin ロールがありますが、 keycloak.token.admin-roles システムプロパティーでカスタマイズできます。

デフォルトでは、 KeycloakTestResourceLifecycleManager は HTTPS を使用して Keycloak インスタンスを初期化しますが、 keycloak.use.https=false で無効にできます。デフォルトのレルム名は quarkus で、クライアント ID quarkus-service-app は、必要に応じて値をカスタマイズするために keycloak.realm および keycloak.service.client システムプロパティーを設定します。

ローカル公開鍵

また、 quarkus-oidc service アプリケーションのテストに、ローカルのインライン公開鍵を使用することもできます。

quarkus.oidc.client-id=test
quarkus.oidc.public-key=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlivFI8qB4D0y2jy0CfEqFyy46R0o7S8TKpsx5xbHKoU1VWg6QkQm+ntyIv1p4kE1sPEQO73+HY8+Bzs75XwRTYL1BmR1w8J5hmjVWjc6R2BTBGAYRPFRhor3kpM6ni2SPmNNhurEAHw7TaqszP5eUF/F9+KEBWkwVta+PZ37bwqSE4sCb1soZFrVz/UT/LF4tYpuVYt3YbqToZ3pZOZ9AX2o1GCG3xwOjkc4x0W7ezbQZdC9iftPxVHR8irOijJRRjcPDtA6vPKpzLl6CyYnsIYPd99ltwxTHjr3npfv/3Lw50bAkbT4HeLFxTx4flEoZLKO/g0bAoV2uqBhkA9xnQIDAQAB

smallrye.jwt.sign.key.location=/privateKey.pem

integration-tests/oidc-tenancy から main のQuarkusリポジトリに privateKey.pem をコピーし、上記 Wiremock のセクションと同様のテストコードを使用してJWTトークンを生成します。必要であれば、独自のテストキーを使用することもできます。

このアプローチは、Wiremockのアプローチと比較して、より限定された範囲をカバーします。例えば、リモート通信コードはカバーされません。

TestSecurity アノテーション

@TestSecurity および @OidcSecurity アノテーションを使用して、注入された JsonWebToken ならびに UserInfo および OidcConfigurationMetadata に依存する service アプリケーションエンドポイントコードをテストできます。

次の依存関係を追加します。

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-test-security-oidc</artifactId>
    <scope>test</scope>
</dependency>
build.gradle
testImplementation("io.quarkus:quarkus-test-security-oidc")

次のようなテストコードを作成します。

import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import io.quarkus.test.common.http.TestHTTPEndpoint;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.quarkus.test.security.oidc.Claim;
import io.quarkus.test.security.oidc.ConfigMetadata;
import io.quarkus.test.security.oidc.OidcSecurity;
import io.quarkus.test.security.oidc.OidcConfigurationMetadata;
import io.quarkus.test.security.oidc.UserInfo;
import io.restassured.RestAssured;

@QuarkusTest
@TestHTTPEndpoint(ProtectedResource.class)
public class TestSecurityAuthTest {

    @Test
    @TestSecurity(user = "userOidc", roles = "viewer")
    public void testOidc() {
        RestAssured.when().get("test-security-oidc").then()
                .body(is("userOidc:viewer"));
    }

    @Test
    @TestSecurity(user = "userOidc", roles = "viewer")
    @OidcSecurity(claims = {
            @Claim(key = "email", value = "user@gmail.com")
    }, userinfo = {
            @UserInfo(key = "sub", value = "subject")
    }, config = {
            @ConfigMetadata(key = "issuer", value = "issuer")
    })
    public void testOidcWithClaimsUserInfoAndMetadata() {
        RestAssured.when().get("test-security-oidc-claims-userinfo-metadata").then()
                .body(is("userOidc:viewer:user@gmail.com:subject:issuer"));
    }

}

ここで、 ProtectedResource クラスは次のようになります。

import io.quarkus.oidc.OidcConfigurationMetadata;
import io.quarkus.oidc.UserInfo;
import org.eclipse.microprofile.jwt.JsonWebToken;

@Path("/service")
@Authenticated
public class ProtectedResource {

    @Inject
    JsonWebToken accessToken;
    @Inject
    UserInfo userInfo;
    @Inject
    OidcConfigurationMetadata configMetadata;

    @GET
    @Path("test-security-oidc")
    public String testSecurityOidc() {
        return accessToken.getName() + ":" + accessToken.getGroups().iterator().next();
    }

    @GET
    @Path("test-security-oidc-claims-userinfo-metadata")
    public String testSecurityOidcWithClaimsUserInfoMetadata() {
        return accessToken.getName() + ":" + accessToken.getGroups().iterator().next()
                + ":" + accessToken.getClaim("email")
                + ":" + userInfo.getString("sub")
                + ":" + configMetadata.get("issuer");
    }
}

@TestSecurity アノテーションは常に使用する必要があり、その user プロパティーは JsonWebToken.getName() として返され、 roles プロパティーは JsonWebToken.getGroups() として返されることに注意してください。 @OidcSecurity アノテーションはオプションであり、追加のトークンクレームおよび UserInfo プロパティーと OidcConfigurationMetadata プロパティーを設定するために使用できます。さらに、 quarkus.oidc.token.issuer プロパティーが設定されている場合、 OidcConfigurationMetadata issuer プロパティー値として使用されます。

不透明なトークンを使用する場合は、次のようにテストできます。

import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import io.quarkus.test.common.http.TestHTTPEndpoint;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.quarkus.test.security.oidc.OidcSecurity;
import io.quarkus.test.security.oidc.TokenIntrospection;
import io.restassured.RestAssured;

@QuarkusTest
@TestHTTPEndpoint(ProtectedResource.class)
public class TestSecurityAuthTest {

    @Test
    @TestSecurity(user = "userOidc", roles = "viewer")
    @OidcSecurity(introspectionRequired = true,
        introspection = {
            @TokenIntrospection(key = "email", value = "user@gmail.com")
        }
    )
    public void testOidcWithClaimsUserInfoAndMetadata() {
        RestAssured.when().get("test-security-oidc-claims-userinfo-metadata").then()
                .body(is("userOidc:viewer:userOidc:viewer"));
    }

}

ここで、 ProtectedResource クラスは次のようになります。

import io.quarkus.oidc.TokenIntrospection;
import io.quarkus.security.identity.SecurityIdentity;

@Path("/service")
@Authenticated
public class ProtectedResource {

    @Inject
    SecurityIdentity securityIdentity;
    @Inject
    TokenIntrospection introspection;

    @GET
    @Path("test-security-oidc-opaque-token")
    public String testSecurityOidcOpaqueToken() {
        return securityIdentity.getPrincipal().getName() + ":" + securityIdentity.getRoles().iterator().next()
            + ":" + introspection.getString("username")
            + ":" + introspection.getString("scope")
            + ":" + introspection.getString("email");
    }
}

@TestSecurity user および roles 属性は TokenIntrospection username および scope プロパティーとして使用可能で、 io.quarkus.test.security.oidc.TokenIntrospection を使用してさらに email などのイントロスペクション応答プロパティーを追加できることに注意してください。

@TestSecurity@OidcSecurity は、例えばこのようにメタアノテーションで組み合わせることができます:

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.METHOD })
    @TestSecurity(user = "userOidc", roles = "viewer")
    @OidcSecurity(introspectionRequired = true,
        introspection = {
            @TokenIntrospection(key = "email", value = "user@gmail.com")
        }
    )
    public @interface TestSecurityMetaAnnotation {

    }

これは、同じセキュリティ設定のセットを複数のテストメソッドで使用する必要がある場合に特に便利です。

ログでエラーを確認する方法

トークン検証エラーの詳細を確認するには、 io.quarkus.oidc.runtime.OidcProvider TRACE レベルのログを有効にしてください。

quarkus.log.category."io.quarkus.oidc.runtime.OidcProvider".level=TRACE
quarkus.log.category."io.quarkus.oidc.runtime.OidcProvider".min-level=TRACE

OidcProvider クライアント初期化エラーの詳細を確認するには、 io.quarkus.oidc.runtime.OidcRecorder TRACE レベルのログを有効にしてください。

quarkus.log.category."io.quarkus.oidc.runtime.OidcRecorder".level=TRACE
quarkus.log.category."io.quarkus.oidc.runtime.OidcRecorder".min-level=TRACE

OpenID Connect プロバイダーへの外部および内部アクセス

OpenID Connect プロバイダーの外部からアクセス可能なトークンおよび他のエンドポイントは、自動検出または設定された URL とは異なる HTTP(S) URL (quarkus.oidc.auth-server-url 内部 URL からの相対 URL) を持つことに注意してください。たとえば、SPA が外部トークンエンドポイントアドレスからトークンを取得し、それをベアラートークンとして Quarkus に送信すると、発行者の検証の失敗がエンドポイントによって報告される場合があります。

このような場合、Keycloak を使用する場合は、外部からアクセス可能なベース URL に設定された KEYCLOAK_FRONTEND_URL システムプロパティーで起動してください。他の Openid Connect プロバイダーと連携している場合は、プロバイダーのドキュメントを確認してください。

'client-id' プロパティーの使用方法

quarkus.oidc.client-id プロパティーは、現在のBearer Tokenを要求した OpenIDConnect クライアントを識別します。これは、ブラウザーで実行されている SPA アプリケーション、またはアクセストークンを Quarkus service アプリケーションに伝播する Quarkus web-app 機密クライアントアプリケーションの場合があります。

このプロパティーは、 service アプリケーションがトークンをリモートで検査することが期待される場合に必要です。これは不透明なトークンの場合は常に当てはまります。ローカルの Json Web Key トークン検証のみが使用される場合、このプロパティーはオプションです。

それでも、エンドポイントがリモートイントロスペクションエンドポイントへのアクセスを必要としない場合でも、このプロパティーを設定することをお勧めします。その背後にある理由は、 client-id が設定されている場合、トークンオーディエンスを検証するために使用でき、トークンの検証が失敗したときにログに含まれるため、長い期間分析対象となる特定のクライアントに発行されたトークンのトレーサビリティが向上するためです。

たとえば、OpenID Connect プロバイダーがトークンオーディエンスを設定する場合、次の設定パターンが推奨されます。

# Set client-id
quarkus.oidc.client-id=quarkus-app
# Token audience claim must contain 'quarkus-app'
quarkus.oidc.token.audience=${quarkus.oidc.client-id}

quarkus.oidc.client-id を設定したが、エンドポイントが OpenID Connect プロバイダーエンドポイントの 1 つへのリモートアクセスを必要としない場合は (イントロスペクション、トークン取得など)、 quarkus.oidc.credentials または同様のプロパティーでクライアントシークレットを設定しないでください。使用されないためです。

Quarkus の web-app アプリケーションには、常に quarkus.oidc.client-id プロパティーが必要である点に注意してください。