Web の用意
HTML と JavaScript だけの画面を、Podman の nginx のコンテナで配ります。このレクチャーでは、画面が「どの User Pool に、どのクライアントとしてログインするか」を読み込んで表示するところまでを用意します。サインアップとログインは、次のレクチャーから足していきます。
画面を配る ブラウザ ◀──index.html・index.js・config.json── nginx のコンテナ(:3000)フレームワークは使いません。画面は public/ に置いたファイルだけで、nginx がそのまま配ります。「どの User Pool に、どのクライアントとしてログインするか」は、setup が書き出す public/config.json で画面に渡します。
このレクチャーで足す・変えるファイルは次のとおりです。
| ファイル | 役割 | |
|---|---|---|
| 作成 | public/index.html | トップの画面。各画面へのリンク。04-04 で Entra ID から戻ってくる受け口にもなる |
| 作成 | public/index.js | トップの画面の動き |
| 作成 | public/lib/config.js | config.json を読み、Cognito の API の入口を求める |
| 作成 | public/style.css | どの画面でも使う見た目 |
| 変更 | .gitignore | 手元にだけ置くファイル(ID・トークン・シークレット) |
| 変更 | compose.yaml | コンテナの定義。Floci から始まり、03 で nginx、04 で entra-local が増える |
| 変更 | scripts/create-user-pool.sh | User Pool と App Client を作り、ID を .cognito.env に残す |
handson/ で作業します。Floci を止めていたときは、起動してから bash scripts/setup.sh で前のレクチャーを終えた状態を作り直します。
podman compose up -dbash scripts/setup.sh # 前のレクチャーまでに作ったものを作り直すこのハンズオンの主題は Cognito なので、画面のファイルは書かずに、ダウンロードして置きます。下のボタンで public/ をダウンロードし、handson/ の中で展開してください(handson/public/ ができます)。
| ファイル | 役割 | |
|---|---|---|
| 作成 | public/index.html | トップの画面。各画面へのリンク。04-04 で Entra ID から戻ってくる受け口にもなる |
| 作成 | public/index.js | トップの画面の動き |
| 作成 | public/lib/config.js | config.json を読み、Cognito の API の入口を求める |
| 作成 | public/style.css | どの画面でも使う見た目 |
このあと、メールボックス・サインアップ・ログインと画面が増えていきます。そのたびに、そのレクチャーの public/ をダウンロードし、handson/ の中で展開して上書きします。
public/ index.html index.js 画面(見た目の HTML と、同じ名前の .js の動き) style.css どの画面でも使う見た目 lib/ どの画面でも使う部品 config.js config.json を読むpublic/lib/config.js…config.jsonを読み、Cognito の API の入口(issuerのオリジン)を求めます。Floci ならhttp://localhost:4566、本物ならhttps://cognito-idp.<リージョン>.amazonaws.comになりますpublic/index.html・public/index.js… トップの画面。いまは、lib/config.jsから受け取った Cognito の API の入口を出すだけです
中身は、ページの最後の「このレクチャーを終えた handson/」で読めます。
画面に設定を渡す
Section titled “画面に設定を渡す”画面は、どの User Pool に、どのクライアントとしてログインするかを public/config.json から読みます。create-user-pool.sh の最後に、.cognito.env と同じ値を public/config.json にも書き出す数行を足します。
scripts/create-user-pool.sh を変更する
Section titled “scripts/create-user-pool.sh を変更する”User Pool と App Client を作り、ID を .cognito.env に残す色の付いた行が、このレクチャーで足す行です
#!/usr/bin/env bash# User Pool と App Client を作り、ID を .cognito.env に書き出す。set -euo pipefailcd "$(dirname "$0")/.."source ./env.sh
POOL_ID=$(aws cognito-idp create-user-pool \ --pool-name practice \ --policies 'PasswordPolicy={MinimumLength=8,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true,RequireSymbols=false}' \ --auto-verified-attributes email \ --query UserPool.Id --output text)
# ブラウザや CLI から使うクライアントはシークレットを持たせない(秘密を守れないため)CLIENT_ID=$(aws cognito-idp create-user-pool-client \ --user-pool-id "$POOL_ID" \ --client-name practice-cli \ --no-generate-secret \ --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \ --prevent-user-existence-errors ENABLED \ --query UserPoolClient.ClientId --output text)
cat > .cognito.env <<ENVexport POOL_ID=$POOL_IDexport CLIENT_ID=$CLIENT_IDENVcat .cognito.env
# 画面が読む設定。どの User Pool に、どのクライアントとしてログインするか(どれもブラウザに渡る値で、秘密ではない)cat > public/config.json <<JSON{ "issuer": "$AWS_ENDPOINT_URL/$POOL_ID", "clientId": "$CLIENT_ID" }JSONissuerはhttp://localhost:4566/<プール ID>(本物ならhttps://cognito-idp.<リージョン>.amazonaws.com/<プール ID>)、clientIdはクライアント ID です。どれもブラウザに渡る値で、秘密ではありませんsetupで User Pool を作り直すたびに書き直されます。画面は読み込み直すだけで、新しい値を使います
public/config.json は手元の環境ごとに中身が違うので、.gitignore に足します。
.gitignore を変更する
Section titled “.gitignore を変更する”手元にだけ置くファイル(ID・トークン・シークレット)色の付いた行が、このレクチャーで足す行です
.cognito.envpublic/config.jsonFloci と画面を起動する
Section titled “Floci と画面を起動する”compose.yaml に 2 つ足します。
flociに、ブラウザからの呼び出しを許すオリジン(CORS)。画面(http://localhost:3000)は Cognito の API(http://localhost:4566)をブラウザから直接呼びます。オリジンが違うので、呼ばれる側の Floci が許す必要があります。本物の Cognito の API は、最初からブラウザからの呼び出しに対応していますpublic/をそのまま配る nginx のコンテナweb。./publicをコンテナの中の nginx の公開フォルダにつなぎ、ポート 3000 で配ります
compose.yaml を変更する
Section titled “compose.yaml を変更する”コンテナの定義。Floci から始まり、03 で nginx、04 で entra-local が増える色の付いた行が、このレクチャーで足す行です
services: floci: image: docker.io/floci/floci:2.4.0 ports: # ほかのマシンから届かないよう、ループバックにだけ公開する(Floci は認証なしで API を受け付ける) - "127.0.0.1:4566:4566" environment: # 画面(http://localhost:3000)から Cognito の API を直接呼べるようにする FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS: http://localhost:3000
web: # 画面(public/)を配るだけの静的サーバー image: docker.io/library/nginx:1.27-alpine ports: - "127.0.0.1:3000:80" volumes: - ./public:/usr/share/nginx/html:ro起動します。Floci は設定が変わったので作り直されます。作り直すと Floci のデータは消える ので、setup をやり直します(ここで setup.sh を育ててきたことが効きます)。この setup で public/config.json も書き出されます。
podman compose up -dbash scripts/setup.sh動作確認する
Section titled “動作確認する”画面に渡す設定が配られているかを確かめます。
curl -s localhost:3000/config.json# { "issuer": "http://localhost:4566/ap-northeast-1_xxxxxxxxx", "clientId": "xxxxxxxxxxxxxxxxxxxxxxxxxx" }http://localhost:3000 を開き、「Cognito の API: http://localhost:4566」と出れば完成です。
このレクチャーを終えた handson/
Section titled “このレクチャーを終えた handson/”// setup が書き出す config.json を読む。どの User Pool に、どのクライアントとしてログインするか(作り直したときに古い値を使わないよう、キャッシュしない)const response = await fetch('/config.json', { cache: 'no-store' });if (!response.ok) { document.body.insertAdjacentHTML('afterbegin', '<p class="error">config.json がありません。<code>bash scripts/setup.sh</code> を流してから、読み込み直してください</p>'); throw new Error('config.json がありません');}export const config = await response.json();
// Cognito の API の入口は、issuer のオリジン(Floci は http://localhost:4566、本物は https://cognito-idp.<リージョン>.amazonaws.com)export const cognitoEndpoint = new URL(config.issuer).origin;<!doctype html><html lang="ja"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Cognito ログインの練習</title> <link rel="stylesheet" href="./style.css"></head><body> <h1>Cognito ログインの練習</h1> <p>Cognito の API: <code id="endpoint">読み込み中…</code></p>
<script type="module" src="./index.js"></script></body></html>import { cognitoEndpoint } from './lib/config.js';
document.querySelector('#endpoint').textContent = cognitoEndpoint;body { font-family: system-ui, sans-serif; max-width: 44rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.6; }form, section { border: 1px solid #ccc; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; }input { display: block; margin: 0.25rem 0 0.75rem; padding: 0.4rem; width: 100%; box-sizing: border-box; }button { margin: 0 0.5rem 0.5rem 0; }.message { margin: 0.5rem 0 0; }.error { color: #b91c1c; }pre { background: #f4f4f4; padding: 0.75rem; overflow-x: auto; white-space: pre-wrap; word-break: break-all; }#!/usr/bin/env bash# User Pool と App Client を作り、ID を .cognito.env に書き出す。set -euo pipefailcd "$(dirname "$0")/.."source ./env.sh
POOL_ID=$(aws cognito-idp create-user-pool \ --pool-name practice \ --policies 'PasswordPolicy={MinimumLength=8,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true,RequireSymbols=false}' \ --auto-verified-attributes email \ --query UserPool.Id --output text)
# ブラウザや CLI から使うクライアントはシークレットを持たせない(秘密を守れないため)CLIENT_ID=$(aws cognito-idp create-user-pool-client \ --user-pool-id "$POOL_ID" \ --client-name practice-cli \ --no-generate-secret \ --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \ --prevent-user-existence-errors ENABLED \ --query UserPoolClient.ClientId --output text)
cat > .cognito.env <<ENVexport POOL_ID=$POOL_IDexport CLIENT_ID=$CLIENT_IDENVcat .cognito.env
# 画面が読む設定。どの User Pool に、どのクライアントとしてログインするか(どれもブラウザに渡る値で、秘密ではない)cat > public/config.json <<JSON{ "issuer": "$AWS_ENDPOINT_URL/$POOL_ID", "clientId": "$CLIENT_ID" }JSON#!/usr/bin/env bash# Floci のデータはメモリにあり、止めると消える。ここまでのレクチャーで作ったものを、順に作り直す。# レクチャーを 1 つ終えるたびに、そのレクチャーで作ったものを 1 行ずつ足していく。set -euo pipefailcd "$(dirname "$0")/.."
bash scripts/create-user-pool.sh.cognito.envpublic/config.jsonservices: floci: image: docker.io/floci/floci:2.4.0 ports: # ほかのマシンから届かないよう、ループバックにだけ公開する(Floci は認証なしで API を受け付ける) - "127.0.0.1:4566:4566" environment: # 画面(http://localhost:3000)から Cognito の API を直接呼べるようにする FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS: http://localhost:3000
web: # 画面(public/)を配るだけの静的サーバー image: docker.io/library/nginx:1.27-alpine ports: - "127.0.0.1:3000:80" volumes: - ./public:/usr/share/nginx/html:ro# aws CLI と SDK の向き先を Floci に変える。`source ./env.sh` で読み込む。# Floci は認証情報の中身を確かめないので、キーはダミーでよい(本物のキーを入れない)。export AWS_ENDPOINT_URL=http://localhost:4566export AWS_ACCESS_KEY_ID=testexport AWS_SECRET_ACCESS_KEY=testexport AWS_REGION=ap-northeast-1export AWS_PAGER=""よくある質問
Section titled “よくある質問”画面を開いたら何も表示されません
config.json が無いときは、画面の上に「config.json がありません」と出ます。bash scripts/setup.sh を流してから、読み込み直してください。config.json に書かれた User Pool が Floci に無いときも、画面の呼び出しは全部失敗します。Floci を作り直したときは bash scripts/setup.sh をやり直し、画面を読み込み直してください。開発者ツールの Console に CORS のエラーが出ているときは、compose.yaml に FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS を足したあとに podman compose up -d で Floci を作り直したかを確かめてください。
podman compose up -d で、ポート 3000 が使えないと出ます
ほかのプログラムがポート 3000 を使っています。準備 のコマンドで、待ち受けているプログラムを確かめてください。
ファイルを変えたのに、画面が変わりません
macOS の Podman では、public/ のファイルを置き換えてから nginx が新しい中身を返すまでに、数秒かかることがあります(エディタによっては、保存のときにファイルを置き換えます)。数秒待ってから、画面を読み込み直してください。