コンテンツにスキップ

再利用可能にする

再利用可能にする

04-02〜04-04 で手で打ったコマンドを、スクリプトにします。Floci を作り直すと、User Pool と一緒に IdP の登録や App Client の設定も消えます。entra-local のアプリとユーザーはボリュームに残りますが、podman compose down -v で消したときにも戻せるようにします。最後に setup.sh に足して、bash scripts/setup.sh 1 回で、Entra ID でログインできる状態まで作り直せるようにします。

足すファイルは次のとおりです。

ファイル役割
作成scripts/entra-create-user.shentra-local にユーザーを作る
作成scripts/entra-register-app.shentra-local に「Cognito から使うアプリ」を登録する
作成scripts/register-entra.shentra-local を User Pool の外部 IdP として登録する
作成scripts/update-client.shApp Client に Hosted UI の設定を足す(IdP が増えるたびに流す)
変更scripts/setup.shここまでに作ったものを Floci に作り直す。レクチャーごとに 1 行増える

handson/ で作業します。

ターミナルウィンドウ
podman compose up -d
curl -s http://localhost:8443/health # "status":"ok" が返ってから次へ
source ./env.sh

04-02 のアプリの登録とシークレットの作成を scripts/entra-register-app.sh にします。entra-local のデータはボリュームに残るので、.entra.env に控えたアプリがまだあれば、登録し直さずにそれを使います(流すたびに同じ名前のアプリが増えないように)。

scripts/entra-register-app.sh を作成する

Section titled “scripts/entra-register-app.sh を作成する”

entra-local に「Cognito から使うアプリ」を登録する

scripts/entra-register-app.sh
#!/usr/bin/env bash
# entra-local に「Cognito から使うアプリ」を登録し、クライアント ID とシークレットを .entra.env に残す。
# Entra ポータルの「アプリの登録」→「新規登録」→「証明書とシークレット」に当たる操作。
set -euo pipefail
cd "$(dirname "$0")/.."
ENTRA=http://localhost:8443
# entra-local のデータはボリュームに残る。前に登録したアプリがまだあれば、それを使い続ける
# (流すたびに同じ名前のアプリが増えないように)。新しく登録し直したいときは .entra.env を消す
if [ -f .entra.env ]; then
source ./.entra.env
if curl -fsS -o /dev/null "$ENTRA/admin/api/apps/$ENTRA_CLIENT_ID" 2>/dev/null; then
echo "登録済みのアプリを使います(クライアント ID: ${ENTRA_CLIENT_ID})。登録し直すなら .entra.env を消してから実行してください"
exit 0
fi
fi
# リダイレクト URI は Cognito(Floci)の idpresponse。本物なら https://<domain>.auth.<region>.amazoncognito.com/oauth2/idpresponse
APP_ID=$(curl -fsS -X POST "$ENTRA/admin/api/apps" -H 'content-type: application/json' -d '{
"displayName": "Cognito (Floci)",
"isConfidential": true,
"redirectUris": [{ "uri": "http://localhost:4566/cognito-idp/oauth2/idpresponse", "type": "web" }]
}' | jq -r .id)
# シークレットの値は作ったときに一度だけ返る(本物の Entra と同じ)。ここで控えておく
SECRET=$(curl -fsS -X POST "$ENTRA/admin/api/apps/$APP_ID/secrets" -H 'content-type: application/json' \
-d '{"displayName":"cognito"}' | jq -r .secretText)
cat > .entra.env <<ENV
export ENTRA_TENANT_ID=11111111-1111-1111-1111-111111111111
export ENTRA_CLIENT_ID=$APP_ID
export ENTRA_CLIENT_SECRET=$SECRET
ENV
echo "登録しました(クライアント ID: ${APP_ID})。シークレットは .entra.env にあります"

04-03 のユーザーの作成を scripts/entra-create-user.sh にします。既にいるときは作らずに、そのユーザーを表示します。

scripts/entra-create-user.sh を作成する

Section titled “scripts/entra-create-user.sh を作成する”

entra-local にユーザーを作る

scripts/entra-create-user.sh
#!/usr/bin/env bash
# entra-local にユーザーを作る。使い方: bash scripts/entra-create-user.sh <名前(英小文字)> <表示名>
# entra-local のデータはボリュームに残るので、既にいるときは作らずにそのユーザーを表示する。
set -euo pipefail
NAME=$1
DISPLAY=${2:-$1}
UPN="$NAME@entralocal.dev"
ENTRA=http://localhost:8443
BODY=$(mktemp)
trap 'rm -f "$BODY"' EXIT
STATUS=$(curl -sS -o "$BODY" -w '%{http_code}' -X POST "$ENTRA/admin/api/users" -H 'content-type: application/json' -d "{
\"userPrincipalName\": \"$UPN\",
\"displayName\": \"$DISPLAY\",
\"mail\": \"$UPN\",
\"password\": \"Passw0rd!\"
}")
case "$STATUS" in
201)
jq '{ id, userPrincipalName }' "$BODY"
;;
409)
echo "$UPN は既にいます(entra-local のデータはボリュームに残ります)"
curl -fsS "$ENTRA/admin/api/users" | jq --arg upn "$UPN" '.value[] | select(.userPrincipalName == $upn) | { id, userPrincipalName }'
;;
*)
echo "ユーザーを作れませんでした(HTTP $STATUS)" >&2
cat "$BODY" >&2
exit 1
;;
esac

04-04 の App Client の設定の変更を scripts/update-client.sh にします。--supported-identity-providers には、User Pool に登録してある IdP を全部並べます。IdP が増えても、書き直さずに流し直すだけで済みます。

App Client に Hosted UI の設定を足す(IdP が増えるたびに流す)

scripts/update-client.sh
#!/usr/bin/env bash
# App Client に、Hosted UI(認可コードフロー)でログインするための設定を足す。
# UpdateUserPoolClient は「渡さなかった設定を既定値に戻す」API なので、毎回すべての設定を渡し直す。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
# Cognito 自身のログイン画面(COGNITO)と、User Pool に登録してある外部 IdP を全部選べるようにする
PROVIDERS=$(aws cognito-idp list-identity-providers --user-pool-id "$POOL_ID" \
--query 'Providers[].ProviderName' --output text)
ARGS=(
--user-pool-id "$POOL_ID"
--client-id "$CLIENT_ID"
# 02-03 で付けたログインの方法と設定。渡し直さないと既定値に戻り、CLI や画面のフォームからログインできなくなる
--explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH
--prevent-user-existence-errors ENABLED
--supported-identity-providers COGNITO $PROVIDERS
# ログインのあとに戻ってくる URL。ここに無い URL へは戻せない(認可コードを盗まれないため)
--callback-urls http://localhost:3000/
--logout-urls http://localhost:3000/
--allowed-o-auth-flows code
--allowed-o-auth-scopes openid email profile
--allowed-o-auth-flows-user-pool-client
)
# custom:entra_oid をトークンに載せるには、読める属性に入れておく
ARGS+=(--read-attributes email email_verified name preferred_username custom:entra_oid)
aws cognito-idp update-user-pool-client "${ARGS[@]}" \
--query 'UserPoolClient.{IdPs:SupportedIdentityProviders,Callback:CallbackURLs,Flows:AllowedOAuthFlows}'

04-04 のカスタム属性の追加と IdP の登録を scripts/register-entra.sh にします。カスタム属性はあれば足さず、IdP は登録済みなら update-identity-provider で上書きします。最後に update-client.sh を呼びます。

entra-local を User Pool の外部 IdP として登録する

scripts/register-entra.sh
#!/usr/bin/env bash
# entra-local を User Pool の外部 IdP(OIDC)として登録し、アプリのクライアントで選べるようにする。
# 先に bash scripts/entra-register-app.sh(Entra 側にアプリを登録する)を済ませておく。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.entra.env
source ./.cognito.env
# Entra のユーザー ID(oid)を入れておく場所を User Pool に足す。カスタム属性は足せるが、消したり型を変えたりはできない
if ! aws cognito-idp describe-user-pool --user-pool-id "$POOL_ID" \
--query 'UserPool.SchemaAttributes[].Name' --output text | tr '\t' '\n' | grep -qx 'custom:entra_oid'; then
aws cognito-idp add-custom-attributes --user-pool-id "$POOL_ID" \
--custom-attributes Name=entra_oid,AttributeDataType=String,Mutable=true
fi
# v2.0 の issuer はテナントごとに決まる。マルチテナントの common ではなく、自分のテナント ID を入れる
ISSUER=http://localhost:8443/$ENTRA_TENANT_ID/v2.0
# ブラウザが通る authorize だけは localhost。ほかは Floci がコンテナの中から、サービス名 entra-local で呼ぶ
BROWSER=http://localhost:8443
BACKEND=http://entra-local:8443
DETAILS="client_id=$ENTRA_CLIENT_ID,client_secret=$ENTRA_CLIENT_SECRET,authorize_scopes=openid email profile,oidc_issuer=$ISSUER,attributes_request_method=GET,authorize_url=$BROWSER/$ENTRA_TENANT_ID/oauth2/v2.0/authorize,token_url=$BACKEND/$ENTRA_TENANT_ID/oauth2/v2.0/token,attributes_url=$BACKEND/graph/oidc/userinfo,jwks_uri=$BACKEND/$ENTRA_TENANT_ID/discovery/v2.0/keys"
MAPPING="email=email,name=name,preferred_username=preferred_username,custom:entra_oid=oid,username=sub"
# もう一度実行したときに重複で止まらないよう、登録済みなら作り直さずに設定を上書きする
if aws cognito-idp describe-identity-provider --user-pool-id "$POOL_ID" --provider-name EntraID > /dev/null 2>&1; then
aws cognito-idp update-identity-provider --user-pool-id "$POOL_ID" --provider-name EntraID \
--provider-details "$DETAILS" --attribute-mapping "$MAPPING" > /dev/null
else
aws cognito-idp create-identity-provider --user-pool-id "$POOL_ID" --provider-name EntraID --provider-type OIDC \
--provider-details "$DETAILS" --attribute-mapping "$MAPPING" > /dev/null
fi
# アプリのクライアントで EntraID を選べるようにする
bash scripts/update-client.sh
echo "EntraID を登録しました"

3 つのスクリプトを setup.sh に足します。どれも、既にあれば作らずに使うので、何度流しても構いません。

ここまでに作ったものを Floci に作り直す。レクチャーごとに 1 行増える色の付いた行が、このレクチャーで足す行です

scripts/setup.sh
#!/usr/bin/env bash
# Floci のデータはメモリにあり、止めると消える。ここまでのレクチャーで作ったものを、順に作り直す。
# レクチャーを 1 つ終えるたびに、そのレクチャーで作ったものを 1 行ずつ足していく。
set -euo pipefail
cd "$(dirname "$0")/.."
bash scripts/create-user-pool.sh
bash scripts/entra-register-app.sh
bash scripts/entra-create-user.sh taro '山田 太郎'
bash scripts/register-entra.sh

Floci を作り直して(User Pool・IdP の登録・App Client の設定が消える)、setup で作り直します。

ターミナルウィンドウ
podman compose down
podman compose up -d
curl -s http://localhost:8443/health # "status":"ok" が返ってから次へ
bash scripts/setup.sh

最後に EntraID を登録しました と出れば完成です。http://localhost:3000 の「ログイン」を開き(開いていたら読み込み直し)、「Entra ID でログイン」で taro@entralocal.dev / Passw0rd! を入れると、ログイン中の画面に移ります。

このレクチャーを終えた handson/

Section titled “このレクチャーを終えた handson/”
このレクチャーを終えた handson/コードをダウンロード
// 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 });
}
// Hosted UI の仕組み(認可コード + PKCE)で、外部 IdP(Entra ID)でログインする。流れを目で追うため、ライブラリを使わずに書く
import { config } from './config.js';
import { saveTokens } from './tokens.js';
// ログインのあとに戻ってくる URL。App Client の callback URL に登録したものと同じにする
export const redirectUri = `${location.origin}/`;
function base64url(bytes) {
return btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function randomString() {
return base64url(crypto.getRandomValues(new Uint8Array(32)));
}
// 認可・トークンのエンドポイントは discovery が教えてくれる(本物の Cognito でも Floci でも同じ書き方)
const discovery = await (await fetch(`${config.issuer}/.well-known/openid-configuration`)).json();
export async function hostedLogin(identityProvider) {
// verifier は手元に残し、そのハッシュ(challenge)だけを渡す。
// 認可コードを横取りされても、verifier を知らなければトークンに換えられない
const verifier = randomString();
const challenge = base64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
const state = randomString();
sessionStorage.setItem('pkce', JSON.stringify({ verifier, state }));
const params = {
client_id: config.clientId,
response_type: 'code',
redirect_uri: redirectUri,
scope: 'openid email profile',
state,
code_challenge: challenge,
code_challenge_method: 'S256',
};
// identity_provider を付けると、Cognito のログイン画面を飛ばしてその IdP へ直行する
if (identityProvider) params.identity_provider = identityProvider;
const url = new URL(discovery.authorization_endpoint);
url.search = new URLSearchParams(params);
location.assign(url);
}
// Hosted UI から ?code=...&state=... を付けて戻ってきたら、認可コードをトークンに換えて保存する。保存できたら true を返す
export async function handleCallback() {
const params = new URLSearchParams(location.search);
if (!params.has('code') && !params.has('error')) return false;
// 認可コードを URL に残さない(リロードや共有で漏れないように)
history.replaceState(null, '', redirectUri);
if (params.has('error')) {
document.querySelector('#message').textContent = `ログインに失敗しました(${params.get('error')})`;
return false;
}
const saved = JSON.parse(sessionStorage.getItem('pkce') ?? '{}');
sessionStorage.removeItem('pkce');
// 自分が出したリクエストへの応答かを state で確かめる(CSRF 対策)
if (params.get('state') !== saved.state) {
document.querySelector('#message').textContent = 'ログインをやり直してください(state が一致しません)';
return false;
}
const response = await fetch(discovery.token_endpoint, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: config.clientId,
code: params.get('code'),
redirect_uri: redirectUri,
code_verifier: saved.verifier,
}),
});
const json = await response.json();
if (!response.ok) {
document.querySelector('#message').textContent = `ログインに失敗しました(${json.error})`;
return false;
}
// トークンエンドポイントの応答は snake_case。パスワードでログインしたときと同じ形にそろえて持つ
saveTokens({ idToken: json.id_token, accessToken: json.access_token, refreshToken: json.refresh_token });
return true;
}
// Hosted UI 側のログイン状態(Cookie)も消す。消さないと、次に Hosted UI へ行ったとき画面が出ずに素通りする
export function hostedLogout() {
const url = new URL(discovery.authorization_endpoint.replace('/oauth2/authorize', '/logout'));
url.search = new URLSearchParams({ client_id: config.clientId, logout_uri: redirectUri });
location.assign(url);
}
// ログインで受け取ったトークンを、どの画面からも読めるように保存する
// 練習なので sessionStorage に置く(タブを閉じると消える)。XSS があると読まれてしまう場所なので、本番では置き場所を検討する
export function getTokens() {
return JSON.parse(sessionStorage.getItem('tokens') ?? 'null');
}
export function saveTokens(tokens) {
if (tokens) sessionStorage.setItem('tokens', JSON.stringify(tokens));
else sessionStorage.removeItem('tokens');
}
// JWT の真ん中(ペイロード)を読む。署名は確かめない(表示するだけなので)
export function decodeJwt(token) {
const payload = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
return JSON.parse(decodeURIComponent(escape(atob(payload))));
}
<!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>ログイン中の画面</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>ログイン中の画面</h1>
<p id="status">ログインしていません。<a href="./login.html">ログイン</a>してください</p>
<section>
<h2>ID トークンの中身</h2>
<pre id="id-token">ログインすると表示します</pre>
<button id="logout">ログアウト</button>
</section>
<p><a href="./">トップへ</a></p>
<script type="module" src="./home.js"></script>
</body>
</html>
import { config } from './lib/config.js';
import { client, RevokeTokenCommand } from './lib/cognito.js';
import { getTokens, saveTokens, decodeJwt } from './lib/tokens.js';
import { hostedLogout } from './lib/hosted-ui.js';
const tokens = getTokens();
if (tokens) {
const claims = decodeJwt(tokens.idToken);
document.querySelector('#status').textContent = `${claims['cognito:username']} としてログイン中`;
document.querySelector('#id-token').textContent = JSON.stringify(claims, null, 2);
}
document.querySelector('#logout').addEventListener('click', async () => {
// 手元から消す前に、リフレッシュトークンを Cognito で取り消す(盗まれていても使えなくする)
if (tokens) await client.send(new RevokeTokenCommand({ ClientId: config.clientId, Token: tokens.refreshToken }));
saveTokens(null);
// Entra ID でログインしたときのために、Hosted UI 側のログイン状態も消す(そのあとトップに戻る)
hostedLogout();
});
<!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>
<li><a href="./login.html">ログイン</a></li>
<li><a href="./home.html">ログイン中の画面</a></li>
</ul>
<p id="message" class="error"></p>
<script type="module" src="./index.js"></script>
</body>
</html>
import { cognitoEndpoint } from './lib/config.js';
import { handleCallback } from './lib/hosted-ui.js';
document.querySelector('#endpoint').textContent = cognitoEndpoint;
// Entra ID でのログインから ?code=... を付けて戻ってきたら、トークンに換えて、ログイン中の画面へ
if (await handleCallback()) location.replace('./home.html');
<!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="login">
<label>ユーザー名 <input name="username" required></label>
<label>パスワード <input name="password" type="password" required></label>
<button disabled>ログイン</button>
<p class="message"></p>
</form>
<section>
<h2>ほかの方法でログイン</h2>
<button id="entra-login">Entra ID でログイン</button>
</section>
<p><a href="./">トップへ</a></p>
<script type="module" src="./login.js"></script>
</body>
</html>
import { config } from './lib/config.js';
import { client, InitiateAuthCommand } from './lib/cognito.js';
import { formValues, showMessage, showError } from './lib/form.js';
import { saveTokens } from './lib/tokens.js';
import { hostedLogin } from './lib/hosted-ui.js';
document.querySelector('#login').addEventListener('submit', async (event) => {
event.preventDefault();
const { username, password } = formValues(event.target);
try {
const result = await client.send(new InitiateAuthCommand({
ClientId: config.clientId,
AuthFlow: 'USER_PASSWORD_AUTH',
AuthParameters: { USERNAME: username, PASSWORD: password },
}));
// 管理者が作ったユーザーの初回ログインなどでは、トークンの代わりにチャレンジ(ChallengeName)が返る
const auth = result.AuthenticationResult;
if (!auth) return showMessage(event.target, `続けるには追加の手続きが要ります(${result.ChallengeName})`, { error: true });
saveTokens({ idToken: auth.IdToken, accessToken: auth.AccessToken, refreshToken: auth.RefreshToken });
// ログイン中の画面へ
location.assign('./home.html');
} catch (error) {
showError(event.target, error);
}
});
// スクリプトの準備ができてから押せるようにする(その前に押すと、ブラウザがフォームをふつうに送り、パスワードが URL に載ってしまう)
document.querySelector('#login button').disabled = false;
// Cognito に登録した IdP の名前(register-entra.sh の --provider-name)を渡す
document.querySelector('#entra-login').addEventListener('click', () => hostedLogin('EntraID'));
<!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 pipefail
cd "$(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 <<ENV
export POOL_ID=$POOL_ID
export CLIENT_ID=$CLIENT_ID
ENV
cat .cognito.env
# 画面が読む設定。どの User Pool に、どのクライアントとしてログインするか(どれもブラウザに渡る値で、秘密ではない)
cat > public/config.json <<JSON
{ "issuer": "$AWS_ENDPOINT_URL/$POOL_ID", "clientId": "$CLIENT_ID" }
JSON
#!/usr/bin/env bash
# entra-local にユーザーを作る。使い方: bash scripts/entra-create-user.sh <名前(英小文字)> <表示名>
# entra-local のデータはボリュームに残るので、既にいるときは作らずにそのユーザーを表示する。
set -euo pipefail
NAME=$1
DISPLAY=${2:-$1}
UPN="$NAME@entralocal.dev"
ENTRA=http://localhost:8443
BODY=$(mktemp)
trap 'rm -f "$BODY"' EXIT
STATUS=$(curl -sS -o "$BODY" -w '%{http_code}' -X POST "$ENTRA/admin/api/users" -H 'content-type: application/json' -d "{
\"userPrincipalName\": \"$UPN\",
\"displayName\": \"$DISPLAY\",
\"mail\": \"$UPN\",
\"password\": \"Passw0rd!\"
}")
case "$STATUS" in
201)
jq '{ id, userPrincipalName }' "$BODY"
;;
409)
echo "$UPN は既にいます(entra-local のデータはボリュームに残ります)"
curl -fsS "$ENTRA/admin/api/users" | jq --arg upn "$UPN" '.value[] | select(.userPrincipalName == $upn) | { id, userPrincipalName }'
;;
*)
echo "ユーザーを作れませんでした(HTTP $STATUS)" >&2
cat "$BODY" >&2
exit 1
;;
esac
#!/usr/bin/env bash
# entra-local に「Cognito から使うアプリ」を登録し、クライアント ID とシークレットを .entra.env に残す。
# Entra ポータルの「アプリの登録」→「新規登録」→「証明書とシークレット」に当たる操作。
set -euo pipefail
cd "$(dirname "$0")/.."
ENTRA=http://localhost:8443
# entra-local のデータはボリュームに残る。前に登録したアプリがまだあれば、それを使い続ける
# (流すたびに同じ名前のアプリが増えないように)。新しく登録し直したいときは .entra.env を消す
if [ -f .entra.env ]; then
source ./.entra.env
if curl -fsS -o /dev/null "$ENTRA/admin/api/apps/$ENTRA_CLIENT_ID" 2>/dev/null; then
echo "登録済みのアプリを使います(クライアント ID: ${ENTRA_CLIENT_ID})。登録し直すなら .entra.env を消してから実行してください"
exit 0
fi
fi
# リダイレクト URI は Cognito(Floci)の idpresponse。本物なら https://<domain>.auth.<region>.amazoncognito.com/oauth2/idpresponse
APP_ID=$(curl -fsS -X POST "$ENTRA/admin/api/apps" -H 'content-type: application/json' -d '{
"displayName": "Cognito (Floci)",
"isConfidential": true,
"redirectUris": [{ "uri": "http://localhost:4566/cognito-idp/oauth2/idpresponse", "type": "web" }]
}' | jq -r .id)
# シークレットの値は作ったときに一度だけ返る(本物の Entra と同じ)。ここで控えておく
SECRET=$(curl -fsS -X POST "$ENTRA/admin/api/apps/$APP_ID/secrets" -H 'content-type: application/json' \
-d '{"displayName":"cognito"}' | jq -r .secretText)
cat > .entra.env <<ENV
export ENTRA_TENANT_ID=11111111-1111-1111-1111-111111111111
export ENTRA_CLIENT_ID=$APP_ID
export ENTRA_CLIENT_SECRET=$SECRET
ENV
echo "登録しました(クライアント ID: ${APP_ID})。シークレットは .entra.env にあります"
#!/usr/bin/env bash
# entra-local を User Pool の外部 IdP(OIDC)として登録し、アプリのクライアントで選べるようにする。
# 先に bash scripts/entra-register-app.sh(Entra 側にアプリを登録する)を済ませておく。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.entra.env
source ./.cognito.env
# Entra のユーザー ID(oid)を入れておく場所を User Pool に足す。カスタム属性は足せるが、消したり型を変えたりはできない
if ! aws cognito-idp describe-user-pool --user-pool-id "$POOL_ID" \
--query 'UserPool.SchemaAttributes[].Name' --output text | tr '\t' '\n' | grep -qx 'custom:entra_oid'; then
aws cognito-idp add-custom-attributes --user-pool-id "$POOL_ID" \
--custom-attributes Name=entra_oid,AttributeDataType=String,Mutable=true
fi
# v2.0 の issuer はテナントごとに決まる。マルチテナントの common ではなく、自分のテナント ID を入れる
ISSUER=http://localhost:8443/$ENTRA_TENANT_ID/v2.0
# ブラウザが通る authorize だけは localhost。ほかは Floci がコンテナの中から、サービス名 entra-local で呼ぶ
BROWSER=http://localhost:8443
BACKEND=http://entra-local:8443
DETAILS="client_id=$ENTRA_CLIENT_ID,client_secret=$ENTRA_CLIENT_SECRET,authorize_scopes=openid email profile,oidc_issuer=$ISSUER,attributes_request_method=GET,authorize_url=$BROWSER/$ENTRA_TENANT_ID/oauth2/v2.0/authorize,token_url=$BACKEND/$ENTRA_TENANT_ID/oauth2/v2.0/token,attributes_url=$BACKEND/graph/oidc/userinfo,jwks_uri=$BACKEND/$ENTRA_TENANT_ID/discovery/v2.0/keys"
MAPPING="email=email,name=name,preferred_username=preferred_username,custom:entra_oid=oid,username=sub"
# もう一度実行したときに重複で止まらないよう、登録済みなら作り直さずに設定を上書きする
if aws cognito-idp describe-identity-provider --user-pool-id "$POOL_ID" --provider-name EntraID > /dev/null 2>&1; then
aws cognito-idp update-identity-provider --user-pool-id "$POOL_ID" --provider-name EntraID \
--provider-details "$DETAILS" --attribute-mapping "$MAPPING" > /dev/null
else
aws cognito-idp create-identity-provider --user-pool-id "$POOL_ID" --provider-name EntraID --provider-type OIDC \
--provider-details "$DETAILS" --attribute-mapping "$MAPPING" > /dev/null
fi
# アプリのクライアントで EntraID を選べるようにする
bash scripts/update-client.sh
echo "EntraID を登録しました"
#!/usr/bin/env bash
# Floci のデータはメモリにあり、止めると消える。ここまでのレクチャーで作ったものを、順に作り直す。
# レクチャーを 1 つ終えるたびに、そのレクチャーで作ったものを 1 行ずつ足していく。
set -euo pipefail
cd "$(dirname "$0")/.."
bash scripts/create-user-pool.sh
bash scripts/entra-register-app.sh
bash scripts/entra-create-user.sh taro '山田 太郎'
bash scripts/register-entra.sh
#!/usr/bin/env bash
# App Client に、Hosted UI(認可コードフロー)でログインするための設定を足す。
# UpdateUserPoolClient は「渡さなかった設定を既定値に戻す」API なので、毎回すべての設定を渡し直す。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
# Cognito 自身のログイン画面(COGNITO)と、User Pool に登録してある外部 IdP を全部選べるようにする
PROVIDERS=$(aws cognito-idp list-identity-providers --user-pool-id "$POOL_ID" \
--query 'Providers[].ProviderName' --output text)
ARGS=(
--user-pool-id "$POOL_ID"
--client-id "$CLIENT_ID"
# 02-03 で付けたログインの方法と設定。渡し直さないと既定値に戻り、CLI や画面のフォームからログインできなくなる
--explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH
--prevent-user-existence-errors ENABLED
--supported-identity-providers COGNITO $PROVIDERS
# ログインのあとに戻ってくる URL。ここに無い URL へは戻せない(認可コードを盗まれないため)
--callback-urls http://localhost:3000/
--logout-urls http://localhost:3000/
--allowed-o-auth-flows code
--allowed-o-auth-scopes openid email profile
--allowed-o-auth-flows-user-pool-client
)
# custom:entra_oid をトークンに載せるには、読める属性に入れておく
ARGS+=(--read-attributes email email_verified name preferred_username custom:entra_oid)
aws cognito-idp update-user-pool-client "${ARGS[@]}" \
--query 'UserPoolClient.{IdPs:SupportedIdentityProviders,Callback:CallbackURLs,Flows:AllowedOAuthFlows}'
.cognito.env
public/config.json
.entra.env
.entra.*.env
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
entra-local:
# amd64 向けのイメージしか無い。Apple Silicon の Mac ではエミュレーションで動く(起動に少し時間がかかる)
image: ghcr.io/cmaneu/entra-local:0.1.1
platform: linux/amd64
environment:
# Floci はコンテナの中から entra-local を呼ぶ。自己署名証明書を信頼させる手間を省くため、練習では HTTP にする
TLS_ENABLED: "false"
# discovery やトークンの iss に載る URL。ブラウザから見える名前にそろえる
PUBLIC_ORIGIN: http://localhost:8443
# 既定はアカウントを選ぶだけでサインインできる。本物に近づけるため、パスワードを求める
REQUIRE_PASSWORD: "true"
ports:
- "127.0.0.1:8443:8443"
volumes:
# ユーザーやアプリ登録は SQLite に残る(podman compose down でも消えない)。消したいときは podman compose down -v
- entra-local-data:/app/data
volumes:
entra-local-data:
ターミナルウィンドウ
# aws CLI と SDK の向き先を Floci に変える。`source ./env.sh` で読み込む。
# Floci は認証情報の中身を確かめないので、キーはダミーでよい(本物のキーを入れない)。
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
export AWS_REGION=ap-northeast-1
export AWS_PAGER=""
bash scripts/setup.sh が entra-local のところで止まります

entra-local がまだ起動しきっていないことがあります。curl -s http://localhost:8443/health で "status":"ok" が返るのを確かめてから、もう一度流してください。