コンテンツにスキップ

トークンを読む・グループを使う

トークンを読む・グループを使う

ログインに成功すると、Cognito は 3 つのトークンを返します。中身を開いて、それぞれ何のためのものかを確かめます。後半では グループ を作り、トークンにグループが載ることを確かめます。

このレクチャーで足すファイルは次のとおりです。ログインとトークンを読むための小さな道具が 2 つと、グループを作るスクリプトです。

ファイル役割
作成scripts/create-groups.shadmin グループを作り、alice を入れる
作成scripts/decode-jwt.shJWT の中身を読む(署名は確かめない)
作成scripts/login.shパスワードでログインし、トークンを .tokens.json に残す
変更.gitignore手元にだけ置くファイル(ID・トークン・シークレット)
変更scripts/setup.shここまでに作ったものを Floci に作り直す。レクチャーごとに 1 行増える

handson/ で作業します。前のレクチャーから続けているなら、source の行だけで構いません。Floci を止めていたときは、起動してから bash scripts/setup.sh で前のレクチャーを終えた状態を作り直します。

ターミナルウィンドウ
podman compose up -d
curl -s http://localhost:8443/health # "status":"ok" が返ってから次へ(entra-local は起動に数秒かかる)
bash scripts/setup.sh # 前のレクチャーまでに作ったものを作り直す
source ./env.sh && source ./.cognito.env
トークン 誰が読むか 用途
ID トークン アプリ(ログインした画面) 「誰がログインしたか」を知る。名前やメールが入る
アクセストークン API 「この API を呼んでよいか」を判断する
リフレッシュトークン アプリ → Cognito ID・アクセストークンの期限が切れたら、新しいものをもらう

ID トークンとアクセストークンは JWT です。. で区切った 3 つの部分(ヘッダー・ペイロード・署名)からなり、前の 2 つは base64url で符号化した JSON です。

ログインのたびに長いコマンドを打たなくて済むよう、道具を 2 つ作ります。

1 つ目は scripts/login.sh です。initiate-auth でログインし、返ってきたトークン一式(AuthenticationResult)を .tokens.json に保存します。ユーザー名とパスワードは引数($1・$2)で受けます。

パスワードでログインし、トークンを .tokens.json に残す

scripts/login.sh
#!/usr/bin/env bash
# USER_PASSWORD_AUTH でログインし、トークン一式を .tokens.json に保存する。
# 使い方: bash scripts/login.sh <username> <password>
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
aws cognito-idp initiate-auth \
--client-id "$CLIENT_ID" \
--auth-flow USER_PASSWORD_AUTH \
--auth-parameters "USERNAME=$1,PASSWORD=$2" \
--query AuthenticationResult > .tokens.json
echo "saved .tokens.json"

2 つ目は scripts/decode-jwt.sh です。JWT を . で 3 つに分け、前の 2 つを base64url から戻して表示します。署名は確かめません(読むだけです)。

JWT の中身を読む(署名は確かめない)

scripts/decode-jwt.sh
#!/usr/bin/env bash
# JWT のヘッダーとペイロードを読む。署名は確かめない(読むだけ)。
# 使い方: bash scripts/decode-jwt.sh <token> または echo <token> | bash scripts/decode-jwt.sh
set -euo pipefail
TOKEN=${1:-$(cat)}
# JWT は「ヘッダー.ペイロード.署名」。前の 2 つは base64url で符号化した JSON。
# base64url を普通の base64 の文字(+ と /)に戻してから @base64d で戻す。
# iat / exp は UNIX 秒なので、読める形を横に添える
printf '%s' "$TOKEN" | jq -R '
def decode: gsub("-"; "+") | gsub("_"; "/") | @base64d | fromjson;
def readable: reduce ("iat", "auth_time", "exp") as $key (.;
if .[$key] then .["\($key) (読める形)"] = (.[$key] | todate) else . end);
split(".") | { header: (.[0] | decode), payload: (.[1] | decode | readable) }'
  • JSON を扱うのは jq です。split(".") で 3 つに分け、@base64d で base64 を戻し、fromjson で JSON として読みます
  • base64url は、普通の base64 の + と / を URL で使える - と _ に替えたものです。gsub で戻してから @base64d に渡します
  • iat・auth_time・exp は UNIX 秒なので、todate で読める形にして横に添えます

.tokens.json を .gitignore に足します(トークンは手元にだけ置くものです)。

手元にだけ置くファイル(ID・トークン・シークレット)色の付いた行が、このレクチャーで足す行です

.gitignore
.cognito.env
public/config.json
.tokens.json
.entra.env
.entra.*.env

alice でログインし、ID トークンを開きます。

ターミナルウィンドウ
bash scripts/login.sh alice 'Passw0rd!'
jq -r .IdToken .tokens.json | bash scripts/decode-jwt.sh

jq -r .IdToken .tokens.json は、.tokens.json の IdToken を引用符なしで取り出します。

{
"header": { "alg": "RS256", "typ": "JWT", "kid": "ap-northeast-1_1644239d1" },
"payload": {
"sub": "e1f9945e-1e10-4577-a0eb-2ec360231189",
"token_use": "id",
"iss": "http://localhost:4566/ap-northeast-1_1644239d1",
"aud": "299bc23b813f4b93ac5a7165e6",
"cognito:username": "alice",
"email": "alice@example.com",
"email_verified": true,
"exp": 1794554293,
"exp (読める形)": "2026-11-13T05:58:13Z"
}
}

主なクレーム:

  • sub … ユーザーの変わらない ID。ユーザー名は変えられることがあるので、データベースで人を指すときは sub を使います
  • iss … 発行者。どの User Pool が出したトークンかを表します
  • aud … 宛先。ID トークンでは App Client の ID です
  • token_use … id か access。ID トークンとアクセストークンを取り違えないための印です
  • exp … 有効期限(UNIX 秒)。スクリプトが読める形を横に添えています

アクセストークンも開いてみます。

ターミナルウィンドウ
jq -r .AccessToken .tokens.json | bash scripts/decode-jwt.sh

アクセストークンには aud がありません。代わりに client_id と scope が入ります。email も入りません。API に渡すのはこちらなので、API は「誰か」を sub と username で知ることになります。

グループは、ユーザーをまとめて権限を付けるための仕組みです。admin グループを作って alice を入れます。

ターミナルウィンドウ
aws cognito-idp create-group --user-pool-id "$POOL_ID" --group-name admin --description '管理者'
aws cognito-idp admin-add-user-to-group --user-pool-id "$POOL_ID" --username alice --group-name admin
aws cognito-idp admin-list-groups-for-user --user-pool-id "$POOL_ID" --username alice --query 'Groups[].GroupName'

もう一度ログインして、トークンを開きます。

ターミナルウィンドウ
bash scripts/login.sh alice 'Passw0rd!'
jq -r .AccessToken .tokens.json | bash scripts/decode-jwt.sh

ID トークンにもアクセストークンにも "cognito:groups": ["admin"] が入りました。API はこれを見て「管理者だけが使える操作」を許すかを決めます(次のセクションで実装します)。

グループを作って alice を入れる 2 つのコマンドを scripts/create-groups.sh にし、setup.sh に 1 行足します。

admin グループを作り、alice を入れる

scripts/create-groups.sh
#!/usr/bin/env bash
# admin グループを作って alice を入れる。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
aws cognito-idp create-group --user-pool-id "$POOL_ID" --group-name admin \
--description '管理者' > /dev/null
aws cognito-idp admin-add-user-to-group --user-pool-id "$POOL_ID" \
--username alice --group-name admin
aws cognito-idp admin-list-groups-for-user --user-pool-id "$POOL_ID" \
--username alice --query 'Groups[].GroupName'

ここまでに作ったものを 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/create-users.sh
bash scripts/create-groups.sh
bash scripts/entra-register-app.sh
bash scripts/entra-create-user.sh taro '山田 太郎'
bash scripts/register-entra.sh
ターミナルウィンドウ
podman compose down
podman compose up -d
bash scripts/setup.sh # 最後に alice のグループ(["admin"])が出る

このレクチャーを終えた 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
# admin グループを作って alice を入れる。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
aws cognito-idp create-group --user-pool-id "$POOL_ID" --group-name admin \
--description '管理者' > /dev/null
aws cognito-idp admin-add-user-to-group --user-pool-id "$POOL_ID" \
--username alice --group-name admin
aws cognito-idp admin-list-groups-for-user --user-pool-id "$POOL_ID" \
--username alice --query 'Groups[].GroupName'
#!/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
# レクチャーの手順をまとめて流す完成版。alice は管理者が作り、bob は自分でサインアップする。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
# 管理者がユーザーを作る → 初回ログインで NEW_PASSWORD_REQUIRED → 新しいパスワードを決める
aws cognito-idp admin-create-user \
--user-pool-id "$POOL_ID" \
--username alice \
--temporary-password 'Temp1234' \
--user-attributes Name=email,Value=alice@example.com Name=email_verified,Value=true \
--message-action SUPPRESS > /dev/null
SESSION=$(aws cognito-idp initiate-auth \
--client-id "$CLIENT_ID" \
--auth-flow USER_PASSWORD_AUTH \
--auth-parameters USERNAME=alice,PASSWORD=Temp1234 \
--query Session --output text)
aws cognito-idp respond-to-auth-challenge \
--client-id "$CLIENT_ID" \
--challenge-name NEW_PASSWORD_REQUIRED \
--session "$SESSION" \
--challenge-responses USERNAME=alice,NEW_PASSWORD='Passw0rd!' > /dev/null
# ユーザーが自分でサインアップする → メールに届いた確認コードで確定する
aws cognito-idp sign-up \
--client-id "$CLIENT_ID" \
--username bob \
--password 'Passw0rd!' \
--user-attributes Name=email,Value=bob@example.com > /dev/null
CODE=$(bash scripts/read-code.sh bob@example.com)
aws cognito-idp confirm-sign-up --client-id "$CLIENT_ID" --username bob --confirmation-code "$CODE"
aws cognito-idp list-users --user-pool-id "$POOL_ID" \
--query 'Users[].{Username:Username,Status:UserStatus}' --output table
#!/usr/bin/env bash
# JWT のヘッダーとペイロードを読む。署名は確かめない(読むだけ)。
# 使い方: bash scripts/decode-jwt.sh <token> または echo <token> | bash scripts/decode-jwt.sh
set -euo pipefail
TOKEN=${1:-$(cat)}
# JWT は「ヘッダー.ペイロード.署名」。前の 2 つは base64url で符号化した JSON。
# base64url を普通の base64 の文字(+ と /)に戻してから @base64d で戻す。
# iat / exp は UNIX 秒なので、読める形を横に添える
printf '%s' "$TOKEN" | jq -R '
def decode: gsub("-"; "+") | gsub("_"; "/") | @base64d | fromjson;
def readable: reduce ("iat", "auth_time", "exp") as $key (.;
if .[$key] then .["\($key) (読める形)"] = (.[$key] | todate) else . end);
split(".") | { header: (.[0] | decode), payload: (.[1] | decode | readable) }'
#!/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
# USER_PASSWORD_AUTH でログインし、トークン一式を .tokens.json に保存する。
# 使い方: bash scripts/login.sh <username> <password>
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
aws cognito-idp initiate-auth \
--client-id "$CLIENT_ID" \
--auth-flow USER_PASSWORD_AUTH \
--auth-parameters "USERNAME=$1,PASSWORD=$2" \
--query AuthenticationResult > .tokens.json
echo "saved .tokens.json"
#!/usr/bin/env bash
# Floci の SES に届いた確認メールから、指定したアドレス宛ての最新の 6 桁コードを取り出す。
# 使い方: bash scripts/read-code.sh <email>
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
curl -fsS "$AWS_ENDPOINT_URL/_aws/ses" | jq -er --arg to "$1" '
[.messages[] | select(.Destination.ToAddresses | index($to))] | last
| .Body.text_part // "" | capture("(?<code>[0-9]{6})").code' \
|| { echo '確認コードが見つかりません' >&2; exit 1; }
#!/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/create-users.sh
bash scripts/create-groups.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
.tokens.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=""
トークンの中身はだれでも読めるのですか?

はい。JWT のペイロードは暗号化されておらず、base64url を戻せば誰でも読めます。署名は「改ざんされていない」ことを保証するだけです。パスワードや秘密の情報をクレームに入れてはいけません。

カスタム属性はトークンに入りますか?

App Client の「読み取りを許す属性」に含めていれば、ID トークンに custom:xxx の形で入ります。Entra ID のセクションで実際に使います。