チュートリアルA: ReactとTypeScriptを使用したフロントエンドアプリケーション#
このチュートリアルでは、別のドメインのintdash APIにアクセスするサンプルアプリケーションをReactとTypeScriptで開発します。 サンプルアプリケーションはローカル環境で動作させます。
サンプルアプリケーションの概要#
サンプルアプリケーションは次のような配置で実装します。
╔═ docker-compose ════════════════════════════════╗
┌───────┐ request ║ ┌─────┐ root /srv ┌────────────┐ ║
│browser│───────────║─►│nginx│ ──────────────────────► │spa-resource│ ║
└───────┘ ║ └─────┘ ───────────────┐ └────────────┘ ║
║ │ │ ║
║ │ auth_request │ ║
║ │ │ ║
║ ▼ │ /api ║
║ ┌────────────┐ ────────────────────────║─► ┌───────────┐
║ │oauth2-proxy│ ────────────────────────────────║─► │intdash-api│
║ └────────────┘ oidc/oauthflow ║ └───────────┘
║ ║
╚═════════════════════════════════════════════════╝
ユーザーがサンプルアプリケーションにアクセスしたとき、以下のように処理が行われます。
ユーザーがブラウザーからNginxへアクセスします。
Nginxはngx_http_auth_request_moduleを使用して、OAuth2Proxyへ認証を確認します。
OAuth2Proxyはリクエストユーザーの認証状況に応じて、リダイレクトなどの認証処理を実施します。
/apiへのアクセスは、外部に構築されたintdashサーバーへプロキシーします。それ以外についてはNginxのWebリソースを返却します。
必要な開発環境#
Node.js がインストールされていること。
Java実行環境がインストールされ、環境変数
PATHにjavaコマンドへのパスが含まれていること(以下でREST API用ライブラリーを生成する際にJavaによるツールを利用します)。Docker Compose がインストールされていること。
docker composeを使用します。
プロジェクトディレクトリを作成#
Vite を使用してプロジェクト用のディレクトリを作成します。
$ npm create vite@latest # Project name: … <任意のプロジェクト名: custom-app> # Select a framework: › React # Select a variant: › TypeScript + SWC
ディレクトリ内で必要なライブラリーをインストールします。
$ cd <作成したプロジェクト名> $ npm install
REST API用ライブラリーの生成#
intdashサーバーへのアクセスには、intdash REST API用のクライアントライブラリーを使用します。
intdashのREST APIの仕様はOpenAPI Specification形式のファイルで公開されていますので、このファイルをもとにして、ツールを使ってTypeScript用のintdash APIクライアントライブラリーを生成します。
注意
以下で使用する openapi-generator-cli コマンドは内部でJavaアプリケーションを実行するため、Java実行環境がインストールされている必要があります。
以下のコマンドを実行し、OpenAPI Specification形式の仕様ファイルを取得して、それをもとにライブラリーを生成します。
${VERSION}にはv2.6.0のようなintdash APIのバージョン名を指定してください。$ npm install @openapitools/openapi-generator-cli $ VERSION=v2.6.0 $ ./node_modules/.bin/openapi-generator-cli generate \ -g typescript-axios -i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml \ -o ./src/intdash \ --additional-properties=useSingleRequestParameter=true
ライブラリーは、
./src/intdashディレクトリに生成されます。
OAuth2クライアント登録#
これから作成するウェブアプリケーションは、intdashのOAuth2クライアントとして振る舞う必要があります。 そのため、intdashサーバーに、このアプリケーションをOAuth2クライアントとして登録します。
プロジェクトのOAuth2クライアント作成 の手順に従い、以下のように設定してOAuth2クライアントを作成します。
- アプリケーションの種類
[ブラウザーによるユーザー認可(Authorization Code)]を選択します。
- 名前
任意の名前を入力します(例:
my-authorization-code-client)。- トークンエンドポイントの認証方式
client_secret_basicを選択します。- ロール
適切なロールを選択します(例: member)。
- リダイレクトURI
http://127.0.0.1:8080/oauth2/callbackとhttps://127.0.0.1:8443/oauth2/callbackを入力して[追加]をクリックします。
作成後に表示されるクライアントIDとクライアントシークレットは後の手順で使用します。
Tip
ユーザー単位のOAuth2クライアント(プロジェクトを限定しない)を作成する場合は、REST APIを使用してください( OAuth2クライアントを使う 参照)。
OAuth2Proxyの設定#
登録したクライアントをOAuth2Proxyに設定します。設定内容は次のとおりです。設定した内容の詳細や他の設定については OAuth2Proxyのドキュメント を参照してください。
注釈
本チュートリアルでは、作成するアプリケーションに認証機能を提供するためにOAuth2Proxyを使用しますが、これ以外の方法で認証機能を実現してもかまいません。
OAuth2ProxyのCookie Secretを生成します。
$ dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64 | tr -d -- '\n' | tr -- '+/' '-_' ; echo
出力された文字列は次の手順で使用します。
OAuth2Proxyの設定ファイルを作成します。プロジェクトの直下に
oauth2_proxy.cfgという名前で保存します。# アプリケーションのRedirect URLにする。TLSの場合はhttps://127.0.0.1:8443、そうではない場合はhttp://127.0.0.1:8080。 redirect_url = "http://127.0.0.1:8080/oauth2/callback" # "*" に固定。すべてのEmailドメインを許可する email_domains = [ "*" ] # 前の手順で作成したCookieSecretを設定する cookie_secret = "**TODO**" # trueに固定。サインイン画面へのリダイレクトするための画面をスキップする。 skip_provider_button = true # セッションのリフレッシュ間隔。およそアクセストークンの有効期限(通常1h)切れなのでそれより少し短い55分を設定する。 cookie_refresh = "55m"
OAuth2Proxyの設定ファイル(ymlファイル)を作成します。プロジェクトの直下に
oauth2_proxy.ymlという名前で保存します。clientIDとclientSecretには、 OAuth2クライアント登録 で登録したクライアントの情報を入力してください。issuerURLにはintdashサーバーのURL + /api/authを入力します。
injectResponseHeaders: - name: X-Auth-Request-Access-Token values: - claim: access_token providers: # 払い出したクライアントIDを設定する - clientID: "**TODO**" # 払い出したクライアントのシークレットを設定する clientSecret: "**TODO**" code_challenge_method: S256 id: intdash loginURLParameters: - default: - login name: prompt name: intdash oidcConfig: audienceClaims: - aud emailClaim: email groupsClaim: groups insecureSkipNonce: true insecureAllowUnverifiedEmail: true # 必ず `/api/auth` をつける issuerURL: "**TODO:例 https://intdash.example.com/api/auth**" userIDClaim: email provider: oidc scope: openid server: BindAddress: 0.0.0.0:4180 SecureBindAddress: "" TLS: null
Nginxの設定#
Nginxの設定を行います。プロジェクトの直下に
nginx.confという名前で保存します。server { listen 8080; # TLS設定の場合 # listen 8443 ssl; server_name 127.0.0.1; # TLS設定の場合の証明書設定 # ssl_certificate /etc/nginx/ssl/server_api.crt; # ssl_certificate_key /etc/nginx/ssl/server_api.key; location /oauth2/ { # docker-composeで構築するため、proxy_passはdocker内のoauth2-proxyのサービスを指定。 proxy_pass http://oauth2-proxy:4180; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri; } location = /oauth2/auth { proxy_pass http://oauth2-proxy:4180; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Uri $request_uri; proxy_set_header Content-Length ""; proxy_pass_request_body off; } location / { auth_request /oauth2/auth; # リダイレクト先を指定。 error_page 401 =403 http://127.0.0.1:8080/oauth2/sign_in; # TLSの場合のリダイレクト先を指定。 # error_page 401 =403 https://127.0.0.1:8443/oauth2/sign_in; auth_request_set $user $upstream_http_x_auth_request_user; auth_request_set $email $upstream_http_x_auth_request_email; proxy_set_header X-User $user; proxy_set_header X-Email $email; auth_request_set $token $upstream_http_x_auth_request_access_token; proxy_set_header Authorization "Bearer $token"; auth_request_set $auth_cookie $upstream_http_set_cookie; add_header Set-Cookie $auth_cookie; auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; if ($auth_cookie ~* "(; .*)") { set $auth_cookie_name_0 $auth_cookie; set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; } if ($auth_cookie_name_upstream_1) { add_header Set-Cookie $auth_cookie_name_0; add_header Set-Cookie $auth_cookie_name_1; } # ビルド成果物は/srvにマウントする。 root /srv; } # /api はintdash-apiへプロキシする設定例 location /api { # `/` と同様の設定 auth_request /oauth2/auth; # TLSの場合のリダイレクト先を指定。 # error_page 401 =403 https://127.0.0.1:8443/oauth2/sign_in; auth_request_set $user $upstream_http_x_auth_request_user; auth_request_set $email $upstream_http_x_auth_request_email; proxy_set_header X-User $user; proxy_set_header X-Email $email; auth_request_set $token $upstream_http_x_auth_request_access_token; proxy_set_header Authorization "Bearer $token"; auth_request_set $auth_cookie $upstream_http_set_cookie; add_header Set-Cookie $auth_cookie; auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1; if ($auth_cookie ~* "(; .*)") { set $auth_cookie_name_0 $auth_cookie; set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1"; } if ($auth_cookie_name_upstream_1) { add_header Set-Cookie $auth_cookie_name_0; add_header Set-Cookie $auth_cookie_name_1; } # 外部のintdash-apiのアドレス proxy_pass **TODO: 例 https://intdash.example.com**; } }
注釈
Oauth2 Proxyのドキュメントに掲載されている例 とほぼ同じ設定です。
Docker-Composeの設定#
Docker Composeを使用してモジュールを起動します。プロジェクト直下に
docker-compose.ymlという名前で保存します。version: "3.5" services: oauth2-proxy: image: quay.io/oauth2-proxy/oauth2-proxy:v7.6.0 volumes: - ${PWD}/oauth2_proxy.cfg:/etc/oauth2_proxy.cfg - ${PWD}/oauth2_proxy.yml:/etc/oauth2_proxy.yml ports: - 4180:4180/tcp command: - "--config" - "/etc/oauth2_proxy.cfg" - "--alpha-config" - "/etc/oauth2_proxy.yml" networks: oauth2-proxy: {} nginx: image: nginx:latest volumes: # 証明書設定 # - 証明書.pem:/etc/nginx/ssl/server_api.crt # - 証明書の鍵.pem:/etc/nginx/ssl/server_api.key - ${PWD}/nginx.conf:/etc/nginx/conf.d/nginx.conf # 成果物のマウント - ${PWD}/dist:/srv ports: - 8080:8080 # TLSの場合 # - 8443:8443 networks: oauth2-proxy: networks: oauth2-proxy: {}
アプリケーションの実装#
この時点で、ディレクトリ構造は次のようになっています。
.
├── README.md
├── docker-compose.yml
├── index.html
├── nginx.conf
├── oauth2_proxy.cfg
├── oauth2_proxy.yml
├── openapitools.json
├── package-lock.json
├── package.json
├── public
│ └── vite.svg
├── src
│ ├── App.css
│ ├── App.tsx
│ ├── assets
│ │ └── react.svg
│ ├── index.css
│ ├── intdash
│ │ ├── api.ts
│ │ ├── base.ts
│ │ ├── common.ts
│ │ ├── configuration.ts
│ │ ├── git_push.sh
│ │ └── index.ts
│ ├── main.tsx
│ └── vite-env.d.ts
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts
ファイルを修正して簡単なアプリケーションを実装します。
./src/App.tsx を開いて次のように編集します。
import { useEffect, useState } from "react";
import "./App.css";
import { AuthMeApi, User } from "./intdash";
function App() {
// 状態を管理するためのuseStateフックを使用
const [data, setData] = useState<User | any>(null);
// 非同期処理を実行するためのuseEffectフックを使用
useEffect(() => {
const fetchData = async () => {
// APIインスタンスを使ってデータを取得
const authMeApi = new AuthMeApi({
isJsonMime: () => true,
basePath: `/api`,
});
// サインインしたユーザー情報を取得
const { data } = await authMeApi.getMe();
setData(data);
};
fetchData();
}, []);
// データの読み込み中またはデータがない場合の処理
if (!data) {
return <div>Loading...</div>;
}
// サインインユーザーの名前(`name`)を表示する
return (
<>
<div className="card">Hello {data.name}</div>
</>
);
}
export default App;
アプリケーションの実行#
以下のコマンドを実行して、アプリケーションを実行します。
# モジュールのビルド $ npm run build # アプリケーションの起動 $ docker compose up -d
注釈
npm run devなどを使用してフロント部分の開発を進める場合は、API結合部分をインターフェイス化しモックなどですすめます。 今回のサンプルの主旨とは異なるため、その詳細については割愛します。また package.jsonに
tsc && vite build --watchなどを追加することで保存と同時にビルドする設定も可能です。開発に合わせてカスタマイズをします。ウェブブラウザーで http://127.0.0.1:8080 にアクセスします。
リダイレクトされ、intdashのログイン画面が表示されます。ログインします。
再度リダイレクトされ、ログインユーザーの名前が表示されます。
表示されたユーザー名は、サンプルアプリケーションがintdashサーバーから取得したものです。
これで、intdashサーバーにアクセスするアプリケーションを開発できたことが確認できました。