サインアップ
画面から Cognito に直接 サインアップし、メールに届いた確認コードで確認します。サインアップの画面と、確認コードを入れる画面を、別々に作ります。
サインアップ ブラウザ ──SignUp・ConfirmSignUp──▶ Cognito(Floci、:4566)このレクチャーで足す・変えるファイルは次のとおりです。
| ファイル | 役割 | |
|---|---|---|
| 作成 | public/confirm.html | メールに届いた確認コードを入れる画面 |
| 作成 | public/confirm.js | 確認コードの動き |
| 作成 | public/lib/cognito.js | AWS SDK を CDN から読み込み、Floci に向けた client を用意する |
| 作成 | public/lib/form.js | フォームの値を読み、メッセージやエラーを出す |
| 作成 | public/signup.html | サインアップの画面 |
| 作成 | public/signup.js | サインアップの動き |
| 変更 | public/index.html | トップの画面。各画面へのリンク。04-04 で Entra ID から戻ってくる受け口にもなる |
handson/ で作業します。Floci を止めていたときは、起動してから bash scripts/setup.sh で前のレクチャーを終えた状態を作り直します。
podman compose up -dbash scripts/setup.sh # 前のレクチャーまでに作ったものを作り直すサインアップの画面(signup.html)と、メールに届いた確認コードを入れる画面(confirm.html)を置きます。
| ファイル | 役割 | |
|---|---|---|
| 作成 | public/confirm.html | メールに届いた確認コードを入れる画面 |
| 作成 | public/confirm.js | 確認コードの動き |
| 変更 | public/index.html | トップの画面。各画面へのリンク。04-04 で Entra ID から戻ってくる受け口にもなる |
public/index.js | トップの画面の動き | |
| 作成 | public/lib/cognito.js | AWS SDK を CDN から読み込み、Floci に向けた client を用意する |
public/lib/config.js | config.json を読み、Cognito の API の入口を求める | |
| 作成 | public/lib/form.js | フォームの値を読み、メッセージやエラーを出す |
public/mail.html | Floci に届いたメールを読むメールボックス | |
public/mail.js | メールボックスの動き | |
| 作成 | public/signup.html | サインアップの画面 |
| 作成 | public/signup.js | サインアップの動き |
public/style.css | どの画面でも使う見た目 |
上のボタンで、このレクチャーを終えた public/ をダウンロードし、handson/ の中で展開して上書きします(setup が書き出す public/config.json は ZIP に入っていないので、そのまま残ります)。
Cognito の API は、AWS SDK for JavaScript v3(@aws-sdk/client-cognito-identity-provider)で呼びます。npm で入れずに、CDN(esm.sh)からブラウザが直接読み込みます。読み込みと送り先の設定は public/lib/cognito.js にまとめてあります。
import { CognitoIdentityProviderClient, SignUpCommand } from 'https://esm.sh/@aws-sdk/client-cognito-identity-provider@3.1163.0';
const client = new CognitoIdentityProviderClient({ region: 'ap-northeast-1', endpoint: cognitoEndpoint });await client.send(new SignUpCommand({ ClientId: config.clientId, Username, Password, UserAttributes }));- 版(
@3.1163.0)を URL に書いて固定します。書かないと、ある日から新しい版が読み込まれて動きが変わることがあります endpointで、送り先をconfig.jsonのissuerのオリジンに向けます。Floci ならhttp://localhost:4566です。本物の Cognito ならendpointは要りません(regionから決まります)SignUp・ConfirmSignUp・InitiateAuth・RevokeTokenは、AWS の認証情報(署名)なしで、クライアント ID だけで呼べる API です。ブラウザに秘密を置かずに済みます- 失敗すると、
UsernameExistsExceptionなどの名前の例外になります。public/lib/form.jsが、例外の名前ごとに決めた利用者向けの文(ERROR_MESSAGES)を、フォームの中に出します - CDN から読み込むので、画面を開くときはインターネットにつながっている必要があります
画面の流れは次のとおりです。
signup.js…SignUpが成功したら、確認コードを入れる画面へ移ります(ユーザー名を URL の?username=...で渡します)confirm.js… 確認コードをConfirmSignUpで送ります。URL にユーザー名が付いていれば、入れておきます- 送信のボタンは、最初は押せない(
disabled)ようにしてあり、スクリプトがフォームを受け持ったところで押せるようになります。スクリプトはconfig.jsonと CDN の SDK を読み終えてから動くので、その前に押すと、ブラウザがフォームをふつうに送ってしまい、入れたパスワードが URL(?username=...&password=...)に載ってしまうからです
画面から使う
Section titled “画面から使う”http://localhost:3000 を開きます(開いていたら読み込み直し)。
- 「サインアップ」を開き、登録する(例:
carol/carol@example.com/Passw0rd!)。「メールを確認する」の画面に移り、ユーザー名が入っている - 画面のリンクから「メールボックス」を開き、
carol@example.com宛ての確認コードを読む - 違うコード(例:
000000)を入れて「確認する」を押す → フォームに「確認コードが違います」と出る(Network タブの応答はCodeMismatchException) - 正しいコードを入れて「確認する」を押す → 「確認できました。ログインできます」と出る
- 「サインアップ」に戻り、同じユーザー名でもう一度登録してみる → 「このユーザー名は、すでに使われています」と出る(応答は
UsernameExistsException) - 別の名前で、短いパスワード(例:
pass)で登録してみる → 「パスワードは 8 文字以上で、英大文字・英小文字・数字を含めてください」と出る(応答はInvalidPasswordException。02-02 で決めたパスワードポリシーです)
開発者ツールの Network タブで、次を確かめてください。
- 要求は
localhost:4566に飛んでいる - 要求のヘッダーに
x-amz-target: AWSCognitoIdentityProviderService.SignUpが付いている。SDK も、02 の aws CLI と同じ API を呼んでいます localhost:4566への要求の前に、OPTIONSの要求(CORS の下調べ)が出ている
carol は setup では作られません。Floci を作り直したときは、ここでサインアップし直してください。
このレクチャーを終えた handson/
Section titled “このレクチャーを終えた handson/”このレクチャーで Floci に残すものは増えていないので、setup.sh はそのままです。
// Cognito の API を呼ぶ。AWS SDK for JavaScript v3 の Cognito の部分を、CDN(esm.sh)から読み込む。ある日から変わらないよう、版を固定するimport { CognitoIdentityProviderClient } from 'https://esm.sh/@aws-sdk/client-cognito-identity-provider@3.1163.0';import { cognitoEndpoint } from './config.js';
// SignUpCommand・InitiateAuthCommand などのコマンドも、ここから使えるようにするexport * from 'https://esm.sh/@aws-sdk/client-cognito-identity-provider@3.1163.0';
// 送り先を config.json の issuer のオリジン(Floci)に向けたクライアント。// SignUp・InitiateAuth などは、AWS の認証情報(署名)なしで、クライアント ID だけで呼べるexport const client = new CognitoIdentityProviderClient({ region: 'ap-northeast-1', endpoint: cognitoEndpoint });// 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;// フォームの値を読み、フォームの中にメッセージやエラーを出す
export function formValues(form) { return Object.fromEntries(new FormData(form));}
// フォームの中の .message に、文を出すexport function showMessage(form, text, { error = false } = {}) { const message = form.querySelector('.message'); message.textContent = text; message.classList.toggle('error', error);}
// Cognito の例外の名前ごとに、利用者向けの文を決めておく(元の例外は、開発者ツールの Network タブで見られる)const ERROR_MESSAGES = { UsernameExistsException: 'このユーザー名は、すでに使われています', InvalidPasswordException: 'パスワードは 8 文字以上で、英大文字・英小文字・数字を含めてください', CodeMismatchException: '確認コードが違います', ExpiredCodeException: '確認コードの期限が切れています', NotAuthorizedException: 'ユーザー名かパスワードが違います', // ユーザーがいるかどうかを、画面からは分からないようにする(パスワード違いと同じ文にする) UserNotFoundException: 'ユーザー名かパスワードが違います', UserNotConfirmedException: 'メールの確認が済んでいません。メールに届いた確認コードを入れてください',};
export function showError(form, error) { showMessage(form, ERROR_MESSAGES[error.name] ?? `うまくいきませんでした(${error.name})`, { error: true });}<!doctype html><html lang="ja"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>メールを確認する</title> <link rel="stylesheet" href="./style.css"></head><body> <h1>メールを確認する</h1> <p>メールに届いた確認コードを入れます。Floci に届いたメールは <a href="./mail.html" target="_blank">メールボックス</a> で読めます。</p>
<form id="confirm"> <label>ユーザー名 <input name="username" required></label> <label>確認コード <input name="code" inputmode="numeric" required></label> <button disabled>確認する</button> <p class="message"></p> </form>
<p><a href="./">トップへ</a></p>
<script type="module" src="./confirm.js"></script></body></html>import { config } from './lib/config.js';import { client, ConfirmSignUpCommand } from './lib/cognito.js';import { formValues, showMessage, showError } from './lib/form.js';
// サインアップの画面から来たときは、ユーザー名を入れておくdocument.querySelector('#confirm [name=username]').value = new URLSearchParams(location.search).get('username') ?? '';
document.querySelector('#confirm').addEventListener('submit', async (event) => { event.preventDefault(); const { username, code } = formValues(event.target); try { await client.send(new ConfirmSignUpCommand({ ClientId: config.clientId, Username: username, ConfirmationCode: code })); showMessage(event.target, '確認できました。ログインできます'); } catch (error) { showError(event.target, error); }});
// スクリプトの準備ができてから押せるようにする(その前に押すと、ブラウザがフォームをふつうに送り、パスワードが URL に載ってしまう)document.querySelector('#confirm button').disabled = false;<!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> <ul> <li><a href="./mail.html">メールボックス</a></li> <li><a href="./signup.html">サインアップ</a></li> <li><a href="./confirm.html">メールを確認する</a></li> </ul>
<script type="module" src="./index.js"></script></body></html>import { cognitoEndpoint } from './lib/config.js';
document.querySelector('#endpoint').textContent = cognitoEndpoint;<!doctype html><html lang="ja"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>メールボックス</title> <link rel="stylesheet" href="./style.css"> <style> table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ccc; padding: 0.4rem; text-align: left; vertical-align: top; } </style></head><body> <h1>メールボックス</h1> <p>Floci は、Cognito が送るメールを実際には送らず、手元にためておきます。新しいものが上です。</p> <button id="reload">読み込み直す</button>
<table> <thead><tr><th>日時</th><th>宛先</th><th>件名</th><th>本文</th></tr></thead> <tbody id="mails"></tbody> </table>
<p><a href="./">トップへ</a></p>
<script type="module" src="./mail.js"></script></body></html>import { cognitoEndpoint } from './lib/config.js';
async function load() { // Floci にたまったメールの一覧(Floci だけの機能。本物の Cognito には無い) const { messages } = await (await fetch(`${cognitoEndpoint}/_aws/ses`)).json(); const tbody = document.querySelector('#mails'); tbody.replaceChildren(...messages.reverse().map((m) => { const tr = document.createElement('tr'); for (const text of [new Date(m.Timestamp).toLocaleString(), m.Destination.ToAddresses.join(', '), m.Subject, m.Body.text_part]) { const td = document.createElement('td'); td.textContent = text; tr.append(td); } return tr; }));}
document.querySelector('#reload').addEventListener('click', load);await load();<!doctype html><html lang="ja"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>サインアップ</title> <link rel="stylesheet" href="./style.css"></head><body> <h1>サインアップ</h1>
<form id="signup"> <label>ユーザー名 <input name="username" required></label> <label>メール <input name="email" type="email" required></label> <label>パスワード <input name="password" type="password" required></label> <button disabled>登録する</button> <p class="message"></p> </form>
<p><a href="./">トップへ</a></p>
<script type="module" src="./signup.js"></script></body></html>import { config } from './lib/config.js';import { client, SignUpCommand } from './lib/cognito.js';import { formValues, showError } from './lib/form.js';
document.querySelector('#signup').addEventListener('submit', async (event) => { event.preventDefault(); const { username, email, password } = formValues(event.target); try { await client.send(new SignUpCommand({ ClientId: config.clientId, Username: username, Password: password, UserAttributes: [{ Name: 'email', Value: email }], })); // 登録できたら、メールに届いた確認コードを入れる画面へ location.assign(`./confirm.html?username=${encodeURIComponent(username)}`); } catch (error) { showError(event.target, error); }});
// スクリプトの準備ができてから押せるようにする(その前に押すと、ブラウザがフォームをふつうに送り、パスワードが URL に載ってしまう)document.querySelector('#signup button').disabled = false;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 “よくある質問”Amplify を使う場合は?
Amplify(aws-amplify)の signIn も、中では同じように Cognito の API を直接呼んでいます。ただし既定では SRP(パスワードそのものを送らない方式)を使い、送り先も本物の Cognito に固定されています。Floci に向けるには Amplify.configure で userPoolEndpoint を指定し、signIn の authFlowType を USER_PASSWORD_AUTH にします(このハンズオンでは確かめていません)。