サインアップ画面を作る
いまは誰でもノートを作れます。この章では、03 章で設計したとおりに、ログインした人だけがノートを作れる ようにします(認証)。
この節では、Cognito のエミュレーター Floci を起動してユーザープールを作り、ユーザーを登録する サインアップ画面 を作ります。
Floci を起動する
Section titled “Floci を起動する”compose.yaml に Floci を足します。
compose.yaml を変更する
Section titled “compose.yaml を変更する”1010 DB_PATH: /data/notes.db1111 volumes:1212 - db:/data13 # apps/api/scripts/setup-cognito.js が書いた、ユーザープール ID とクライアント ID14 env_file:15 - path: .env16 required: false1317
1418web:1519 # 画面(apps/ui/)を配るだけの静的サーバー2024 volumes:2125 - ./apps/ui:/usr/share/nginx/html:ro2226
27 # Cognito のエミュレーター28 floci:29 image: docker.io/floci/floci:2.4.030 ports:31 # ほかのマシンから届かないよう、ループバックにだけ公開する(Floci は認証なしで API を受け付ける)32 - "127.0.0.1:4566:4566"33 environment:34 # トークンの発行元(iss)を、API のコンテナから届く http://floci:4566 にする35 FLOCI_BASE_URL: http://floci:456636 # 画面(http://localhost:3000)から Cognito の API を直接呼べるようにする37 FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS: http://localhost:300038 healthcheck:39 # 起動が終わったか(/_floci/health が 200 を返すか)を確かめる40 test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/4566 && printf 'GET /_floci/health HTTP/1.0\\r\\n\\r\\n' >&3 && read -r status <&3 && [[ $$status == *' 200 '* ]]"]41 interval: 3s42 timeout: 3s43 retries: 2044
2345volumes:2446 # SQLite のファイルを置く場所。コンテナを作り直しても残る2547 db:env_file… 次に作るスクリプトが書く.env(ユーザープール ID とクライアント ID)を、API のコンテナに渡しますFLOCI_BASE_URL… 発行するトークンの発行元をhttp://floci:4566にします。compose の中では、ほかのコンテナに サービス名(floci)で届くので、API のコンテナから確かめられる名前にしておきますFLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS… 画面(http://localhost:3000)から Floci を直接呼ぶので、その呼び出しを許します
ユーザープールを作る
Section titled “ユーザープールを作る”Cognito の API を呼んで、ユーザープールとアプリケーションクライアントを作るスクリプトです。作った ID を、API が読む .env と、画面が読む apps/ui/config.json に書き出します。
apps/api/scripts/setup-cognito.js を作成する
Section titled “apps/api/scripts/setup-cognito.js を作成する”1// Floci の Cognito に、ユーザープールとアプリケーションクライアントを作り、ID を書き出す。2// Floci は止めるとデータが消えるので、Floci を起動し直したらもう一度実行する。3import { writeFile } from 'node:fs/promises';4
5const endpoint = 'http://localhost:4566';6
7// Cognito の API を 1 つ呼ぶ。Floci は AWS の認証情報を確かめないので、付けずに呼べる8async function cognito(action, params) {9 const response = await fetch(endpoint, {10 method: 'POST',11 headers: {12 'content-type': 'application/x-amz-json-1.1',13 'x-amz-target': `AWSCognitoIdentityProviderService.${action}`,14 },15 body: JSON.stringify(params),16 });17 const json = await response.json();18 if (!response.ok)19 throw new Error(`${action}: ${json.__type} ${json.message}`);20 return json;21}22
23// ユーザープール。メールアドレスでサインインし、サインアップのときにメールで確認コードを送る24const { UserPool } = await cognito('CreateUserPool', {25 PoolName: 'notes',26 UsernameAttributes: ['email'],27 AutoVerifiedAttributes: ['email'],28});29
30// アプリケーションクライアント。ブラウザは秘密を守れないので、クライアントシークレットは持たせない。31// メールアドレスとパスワードでのログイン(USER_PASSWORD_AUTH)を許す32const { UserPoolClient } = await cognito('CreateUserPoolClient', {33 UserPoolId: UserPool.Id,34 ClientName: 'notes',35 GenerateSecret: false,36 ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],37});38
39// API が読む設定(.env)40await writeFile(41 '.env',42 `COGNITO_USER_POOL_ID=${UserPool.Id}\nCOGNITO_CLIENT_ID=${UserPoolClient.ClientId}\n`,43);44// 画面が読む設定。どのユーザープールに、どのクライアントとしてログインするか(どれもブラウザに渡る値で、秘密ではない)45await writeFile(46 'apps/ui/config.json',47 `${JSON.stringify({ issuer: `${endpoint}/${UserPool.Id}`, clientId: UserPoolClient.ClientId })}\n`,48);49console.log(50 `ユーザープール ${UserPool.Id} とクライアント ${UserPoolClient.ClientId} を作り、.env と apps/ui/config.json に書きました`,51);AutoVerifiedAttributes: ['email']… サインアップしたら、メールで確認コードを送りますGenerateSecret: false… ブラウザで動くコードは誰でも中身を見られるので、クライアントシークレットは持たせませんALLOW_USER_PASSWORD_AUTH… メールアドレスとパスワードでのログインを許します(次の節)
サインアップ画面を作る
Section titled “サインアップ画面を作る”画面が使う部品を apps/ui/lib/ に足します。config.js は config.json を読み、cognito.js は Cognito の API を呼びます。
apps/ui/lib/config.js を作成する
Section titled “apps/ui/lib/config.js を作成する”1// apps/api/scripts/setup-cognito.js が書き出す config.json を読む。どのユーザープールに、どのクライアントとしてログインするか(作り直したときに古い値を使わないよう、キャッシュしない)2const response = await fetch('/config.json', { cache: 'no-store' });3if (!response.ok) {4 document.body.insertAdjacentHTML('afterbegin', '<p class="error">config.json がありません。<code>node apps/api/scripts/setup-cognito.js</code> を実行してから、読み込み直してください</p>');5 throw new Error('config.json がありません');6}7export const config = await response.json();8
9// Cognito の API の入口は、issuer のオリジン(Floci は http://localhost:4566、本物は https://cognito-idp.<リージョン>.amazonaws.com)10export const cognitoEndpoint = new URL(config.issuer).origin;apps/ui/lib/cognito.js を作成する
Section titled “apps/ui/lib/cognito.js を作成する”1import { cognitoEndpoint, config } from './config.js';2
3// 画面から Cognito の API を 1 つ呼ぶ。4// サインアップやログインの API は、AWS の認証情報なしで、クライアント ID だけで呼べる5export async function cognito(action, params) {6 const response = await fetch(cognitoEndpoint, {7 method: 'POST',8 headers: {9 'content-type': 'application/x-amz-json-1.1',10 'x-amz-target': `AWSCognitoIdentityProviderService.${action}`,11 },12 body: JSON.stringify({ ClientId: config.clientId, ...params }),13 });14 const json = await response.json();15 // 失敗すると {"__type":"UsernameExistsException","message":"..."} の形で返る16 if (!response.ok) throw new Error(`${json.__type}: ${json.message}`);17 return json;18}- どの操作かを
x-amz-targetヘッダーで伝えます。サインアップやログインの API は、クライアント ID だけで呼べます
apps/ui/signup.html を作成する
Section titled “apps/ui/signup.html を作成する”1<!doctype html>2<html lang="ja">3<head>4 <meta charset="utf-8">5 <meta name="viewport" content="width=device-width, initial-scale=1">6 <title>サインアップ</title>7 <link rel="stylesheet" href="./style.css">8</head>9<body>10 <h1>サインアップ</h1>11
12 <form id="sign-up">13 <label>メールアドレス <input name="email" type="email" required></label>14 <label>パスワード <input name="password" type="password" required></label>15 <button>サインアップ</button>16 </form>17
18 <form id="confirm" hidden>19 <label>確認コード <input name="code" required></label>20 <button>確認する</button>21 </form>22
23 <p id="message" class="message"></p>24
25 <script type="module" src="./signup.js"></script>26</body>27</html>apps/ui/signup.js を作成する
Section titled “apps/ui/signup.js を作成する”1import { cognito } from './lib/cognito.js';2
3const message = document.querySelector('#message');4let email;5
6// 1. メールアドレスとパスワードで登録する。Cognito がメールで確認コードを送る7document.querySelector('#sign-up').addEventListener('submit', async (event) => {8 event.preventDefault();9 const form = new FormData(event.target);10 email = form.get('email');11 try {12 await cognito('SignUp', {13 Username: email,14 Password: form.get('password'),15 UserAttributes: [{ Name: 'email', Value: email }],16 });17 document.querySelector('#confirm').hidden = false;18 message.textContent = '確認コードを送りました';19 } catch (error) {20 message.textContent = error.message;21 }22});23
24// 2. 届いた確認コードを送って、登録を確定する25document.querySelector('#confirm').addEventListener('submit', async (event) => {26 event.preventDefault();27 const form = new FormData(event.target);28 try {29 await cognito('ConfirmSignUp', { Username: email, ConfirmationCode: form.get('code') });30 message.textContent = 'サインアップできました';31 } catch (error) {32 message.textContent = error.message;33 }34});SignUp… メールアドレスとパスワードで登録します。Cognito が確認コードをメールで送りますConfirmSignUp… 届いた確認コードを送ると、登録が確定します
動作確認する
Section titled “動作確認する”ルートで起動し、ユーザープールを作ってから、.env を読ませるためにもう一度起動します。.env はルートに置かれ、compose.yaml が API のコンテナに渡します。
podman compose up -d --build --waitnode apps/api/scripts/setup-cognito.jspodman compose up -d --waitユーザープール us-east-1_6511add1f とクライアント 49d9ff2864944c0cb99ce8f1e4 を作り、.env と apps/ui/config.json に書きましたhttp://localhost:3000/signup.html を開き、alice@example.com とパスワード Passw0rd! で サインアップ を押します。
Floci はメールを本当には送らず、手元にためておきます。http://localhost:4566/_aws/ses を開くと、Your verification code is 273386. のように確認コードが読めます。これを入れて 確認する を押し、「サインアップできました」と出れば大丈夫です。
参考にした公式ドキュメント
Section titled “参考にした公式ドキュメント”この節は、次の公式ドキュメントをもとに書いています。
- Floci … Floci の起動と
FLOCI_*の設定 - Amazon Cognito API: CreateUserPool …
UsernameAttributes・AutoVerifiedAttributes - Amazon Cognito API: CreateUserPoolClient …
GenerateSecret・ExplicitAuthFlows - Amazon Cognito API: SignUp … サインアップ
- Amazon Cognito API: ConfirmSignUp … 確認コードでの確定
- Docker: Compose file reference …
env_file・environment・healthcheck
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”よくある質問
Section titled “よくある質問”画面に「config.json がありません」と出る
node apps/api/scripts/setup-cognito.js をまだ実行していないか、Floci を起動し直してユーザープールが消えています。「動作確認する」の 3 つのコマンドをやり直し、読み込み直してください。
Failed to fetch や ResourceNotFoundException と出る
Floci が止まっているか、起動し直してユーザープールが消えています。「動作確認する」の 3 つのコマンドをやり直してください。