Protect a web application by using OpenID Connect (OIDC) authorization code flow
Quarkus OpenID Connect(OIDC)エクステンションを使用すると、OIDC 認可コードフローメカニズムを使用して、アプリケーションのHTTPエンドポイントを保護できます。
To learn more about the OIDC authorization code flow mechanism, see OIDC code flow mechanism for protecting web applications.
To learn about how well-known social providers such as Google, GitHub, Microsoft, Twitter, Apple, Facebook, and Spotify can be used with Quarkus OIDC, see Configuring Well-Known OpenID Connect Providers. See also, Authentication mechanisms in Quarkus.
If you want to protect your service applications by using OIDC Bearer token authentication, see OIDC Bearer token authentication.
前提条件
このガイドを完成させるには、以下が必要です:
-
約15分
-
IDE
-
JDK 11+ がインストールされ、
JAVA_HOMEが適切に設定されていること -
Apache Maven 3.9.3
-
動作するコンテナランタイム(Docker, Podman)
-
使用したい場合は、 Quarkus CLI
-
ネイティブ実行可能ファイルをビルドしたい場合、MandrelまたはGraalVM(あるいはネイティブなコンテナビルドを使用する場合はDocker)をインストールし、 適切に設定していること
ソリューション
次の章で紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。
git clone -b 3.2 https://github.com/quarkusio/quarkus-quickstarts.git で Git リポジトリーをクローンします。または、https://github.com/quarkusio/quarkus-quickstarts/archive/3.2.zip[アーカイブ] をダウンロードします。
ソリューションは security-openid-connect-web-authentication-quickstart ディレクトリ にあります。
手順
Maven プロジェクトの作成
まず、新しいプロジェクトが必要です。以下のコマンドで新規プロジェクトを作成します。
すでにQuarkusプロジェクトが設定されている場合は、プロジェクトのベースディレクトリーで以下のコマンドを実行することで、プロジェクトに oidc エクステンションを追加することができます。
quarkus extension add 'oidc'
./mvnw quarkus:add-extension -Dextensions='oidc'
./gradlew addExtension --extensions='oidc'
これにより、ビルドファイルに以下が追加されます:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-oidc</artifactId>
</dependency>
implementation("io.quarkus:quarkus-oidc")
アプリケーションの記述
認可コードグラントレスポンスで返されたトークンをすべて注入した、シンプルなJakarta RESTリソースを書いてみましょう:
package org.acme.security.openid.connect.web.authentication;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import org.eclipse.microprofile.jwt.JsonWebToken;
import io.quarkus.oidc.IdToken;
import io.quarkus.oidc.RefreshToken;
@Path("/tokens")
public class TokenResource {
/**
* Injection point for the ID Token issued by the OpenID Connect Provider
*/
@Inject
@IdToken
JsonWebToken idToken;
/**
* Injection point for the Access Token issued by the OpenID Connect Provider
*/
@Inject
JsonWebToken accessToken;
/**
* Injection point for the Refresh Token issued by the OpenID Connect Provider
*/
@Inject
RefreshToken refreshToken;
/**
* Returns the tokens available to the application. This endpoint exists only for demonstration purposes, you should not
* expose these tokens in a real application.
*
* @return a HTML page containing the tokens available to the application
*/
@GET
@Produces("text/html")
public String getTokens() {
StringBuilder response = new StringBuilder().append("<html>")
.append("<body>")
.append("<ul>");
Object userName = this.idToken.getClaim("preferred_username");
if (userName != null) {
response.append("<li>username: ").append(userName.toString()).append("</li>");
}
Object scopes = this.accessToken.getClaim("scope");
if (scopes != null) {
response.append("<li>scopes: ").append(scopes.toString()).append("</li>");
}
response.append("<li>refresh_token: ").append(refreshToken.getToken() != null).append("</li>");
return response.append("</ul>").append("</body>").append("</html>").toString();
}
}
このエンドポイントには、ID、アクセス、リフレッシュの各トークンが注入されています。IDトークンから preferred_username 、アクセストークンから scope 、さらにリフレッシュトークンの可用性ステータスを返します。
基本的にトークンを注入する必要はありません。エンドポイントが ID トークンを使用して現在認証されているユーザーとやりとりする必要がある場合や、アクセス・トークンを使用してこのユーザーに代わってダウンストリーム・サービスにアクセスする必要がある場合にのみ必要となります。
アプリケーションの設定
OIDCエクステンションでは、 src/main/resources ディレクトリにあるはずの application.properties ファイルを使用して設定を定義することができます。
quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.client-id=frontend
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated
これは、アプリケーションへの認証を有効にする際に最もシンプルな設定です。
quarkus.oidc.client-id プロパティは、OIDC プロバイダーが発行する client_id を参照し、 quarkus.oidc.credentials.secret プロパティは、クライアントシークレットを設定します。
OIDC認可コードフローを有効にすることで、ユーザーがOIDCプロバイダーにリダイレクトされて認証されるようQuarkusを設定するために、 quarkus.oidc.application-type プロパティは web-app に設定されています。
最後に、保護したいパスについてQuarkusに伝えるために、 quarkus.http.auth.permission.authenticated パーミッションを設定します。この場合、すべてのパスは、 authenticated ユーザーだけがアクセスできるようにするポリシーで保護されています。詳細については、 セキュリティ認可ガイド を参照してください。
Keycloakサーバーの起動と設定
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.version は 17.0.0 以上に設定する必要があります。
localhost:8180 で Keycloak サーバーにアクセスできるはずです。
Keycloak管理コンソールにアクセスするには、 admin ユーザーとしてログインしてください。ユーザー名は admin 、パスワードは admin とします。
Import the realm configuration file to create a new realm. For more information, see the Keycloak documentation about how to create a new realm.
devモードとJVMモードでアプリケーションを実行
アプリケーションを開発モードで実行するには、次を使用します。
quarkus dev
./mvnw quarkus:dev
./gradlew --console=plain quarkusDev
「開発モード」で遊び終わったら、標準のJavaアプリケーションとして実行することができます。
まず、コンパイルします:
quarkus build
./mvnw install
./gradlew build
そして、実行してみてください:
java -jar target/quarkus-app/quarkus-run.jar
Native モードでアプリケーションを実行
この同じデモをネイティブ・コードにコンパイルすることができます。修正は必要ありません。
これは、生成されたバイナリーにランタイム技術が含まれており、最小限のリソースオーバーヘッドで実行できるように最適化されているため、本番環境にJVMをインストールする必要がないことを意味します。
Compilation will take a bit longer, so this step is disabled by default. You can build again by enabling the native build:
quarkus build --native
./mvnw install -Dnative
./gradlew build -Dquarkus.package.type=native
After getting a cup of coffee, you can run this binary directly:
./target/security-openid-connect-web-authentication-quickstart-runner
アプリケーションのテスト
アプリケーションの動作確認は、ブラウザを起動して以下のURLにアクセスしてください:
すべてが期待通りに動いていれば、Keycloakサーバーにリダイレクトされ、認証が行われます。
To authenticate to the application, type the following credentials when at the Keycloak login page:
-
Username: alice
-
Password: alice
Login ボタンをクリックすると、アプリケーションにリダイレクトされて戻ります。
For more information about writing the integration tests that depend on Dev Services for Keycloak, see the Dev Services for Keycloak section.
概要
Congratulations! You have learned how to set up and use the OIDC authorization code flow mechanism to protect and test application HTTP endpoints. After you have completed this tutorial, explore OIDC Bearer token authentication and other authentication mechanisms.