コンテンツにスキップ

署名を確かめる・トークンを更新する

署名を確かめる・トークンを更新する

トークンの中身は誰でも書き換えられます。API が受け取ったトークンを信じてよいかは、署名 で判断します。Cognito がどの鍵で署名したかは JWKS(公開鍵の一覧)で公開されています。この鍵でトークンを確かめ、書き換えたトークンが弾かれることを見ます。最後にリフレッシュトークンでトークンを更新します。

このレクチャーで足すファイルは次のとおりです。署名を確かめるのも、ほかのスクリプトと同じくシェルスクリプトです。鍵の計算は openssl に任せます。

ファイル役割
作成scripts/refresh.shリフレッシュトークンで新しいトークンをもらう
作成scripts/verify-jwt.shJWKS で JWT の署名・iss・exp を確かめる

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

トークンを 1 組もらっておきます。

ターミナルウィンドウ
bash scripts/login.sh alice 'Passw0rd!'

トークンの iss の後ろに /.well-known/openid-configuration を付けると、その発行者の情報(discovery)が読めます。

ターミナルウィンドウ
curl -s "$AWS_ENDPOINT_URL/$POOL_ID/.well-known/openid-configuration"
{
"issuer": "http://localhost:4566/ap-northeast-1_57965a023",
"jwks_uri": "http://localhost:4566/ap-northeast-1_57965a023/.well-known/jwks.json",
"authorization_endpoint": "http://localhost:4566/cognito-idp/oauth2/authorize",
"token_endpoint": "http://localhost:4566/cognito-idp/oauth2/token"
}

jwks_uri を開くと公開鍵が並んでいます。トークンのヘッダーの kid と同じ kid の鍵が、そのトークンの署名を確かめる鍵です。

ターミナルウィンドウ
curl -s "$AWS_ENDPOINT_URL/$POOL_ID/.well-known/jwks.json"

scripts/verify-jwt.sh を作ります。次の 3 つを確かめます。

  1. JWKS の鍵で署名が正しいか
  2. iss が自分の User Pool か
  3. exp を過ぎていないか

要点は、iss を自分の User Pool から組み立て、そこから discovery → jwks_uri の順に鍵の在りかを知る ことです。トークンの中に書かれた iss を信じて鍵を取りに行くことはしません。

ターミナルウィンドウ
ISSUER="$AWS_ENDPOINT_URL/$POOL_ID"
JWKS_URI=$(curl -fsS "$ISSUER/.well-known/openid-configuration" | jq -r .jwks_uri)
KID=$(b64url_decode "$HEADER" | jq -r .kid)
JWK=$(curl -fsS "$JWKS_URI" | jq -c --arg kid "$KID" '.keys[] | select(.kid == $kid)')

鍵が決まったら、署名を確かめます。

  • JWKS の鍵は、RSA の 2 つの数(n と e)を base64url で書いたものです。openssl はこの形を直接は読めないので、asn1parse -genconf で公開鍵の形(PEM)に組み立てます
  • 署名は「ヘッダー.ペイロード」という文字列の SHA-256 に対するものです(ヘッダーの alg が RS256)。openssl dgst -sha256 -verify で、署名と鍵が合うかを見ます
  • その前に、トークンが base64url の文字だけでできた 3 つの部分か、署名のバイト数が鍵(n)と同じ長さかを確かめます。openssl は署名の後ろに余分なバイトが付いていても通してしまうので、この 2 つを省くと、末尾に文字を足しただけのトークンも OK になります
  • 署名が合ったあとで、ペイロードの iss と exp を確かめます。署名を確かめる前の中身は信じません
ターミナルウィンドウ
openssl dgst -sha256 -verify "$WORK/key.pem" -signature "$WORK/signature" "$WORK/signed"

JWKS で JWT の署名・iss・exp を確かめる

scripts/verify-jwt.sh
#!/usr/bin/env bash
# JWKS を取ってきて、JWT の署名・発行者・有効期限を確かめる。
# 使い方: bash scripts/verify-jwt.sh <token>
# 別の User Pool で確かめたいときは POOL_ID=<プール ID> を付けて実行する(付けた値が .cognito.env より優先)
set -euo pipefail
cd "$(dirname "$0")/.."
GIVEN_POOL_ID=${POOL_ID:-}
source ./env.sh
source ./.cognito.env
POOL_ID=${GIVEN_POOL_ID:-$POOL_ID}
TOKEN=${1:?使い方: bash scripts/verify-jwt.sh <トークン>}
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
ng() { echo "NG: $*" >&2; exit 1; }
# base64url → バイト列。+ と / に戻し、= で 4 の倍数の長さにそろえてから戻す
b64url_decode() {
local s
s=$(printf '%s' "$1" | tr '_-' '/+')
while (( ${#s} % 4 )); do s+='='; done
printf '%s' "$s" | openssl base64 -d -A
}
# base64url → 16 進の文字列(鍵の数を openssl に渡すため)
b64url_hex() { b64url_decode "$1" | od -An -v -tx1 | tr -d ' \n'; }
# base64url の文字(A-Z a-z 0-9 - _)だけでできた 3 つの部分か。= や空白が混ざったものは受け付けない
[[ $TOKEN =~ ^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$ ]] \
|| ng "JWT の形(ヘッダー.ペイロード.署名)になっていません"
IFS=. read -r HEADER PAYLOAD SIGNATURE <<< "$TOKEN"
# Floci の iss は http://localhost:4566/<プール ID>。本物なら https://cognito-idp.<region>.amazonaws.com/<プール ID>
# トークンの中の iss ではなく、自分の User Pool から組み立てる
ISSUER="$AWS_ENDPOINT_URL/$POOL_ID"
# 1. 鍵を選ぶ。鍵の在りかは discovery(<iss>/.well-known/openid-configuration)が教えてくれる
JWKS_URI=$(curl -fsS "$ISSUER/.well-known/openid-configuration" | jq -r .jwks_uri) \
|| ng "discovery を読めませんでした($ISSUER)"
ALG=$(b64url_decode "$HEADER" | jq -r .alg)
KID=$(b64url_decode "$HEADER" | jq -r .kid)
[[ $ALG == RS256 ]] || ng "alg が RS256 ではありません($ALG)"
JWK=$(curl -fsS "$JWKS_URI" | jq -c --arg kid "$KID" '.keys[] | select(.kid == $kid)')
[[ -n $JWK ]] || ng "JWKS に kid が $KID の鍵がありません"
# 2. 署名を確かめる。JWK(n と e)から openssl が読める公開鍵(PEM)を組み立て、
# 「ヘッダー.ペイロード」の SHA-256 と署名が合うかを見る
cat > "$WORK/key.conf" <<CONF
asn1 = SEQUENCE:public_key
[public_key]
algorithm = SEQUENCE:rsa_algorithm
key = BITWRAP,SEQUENCE:rsa_key
[rsa_algorithm]
oid = OID:rsaEncryption
parameters = NULL
[rsa_key]
n = INTEGER:0x$(b64url_hex "$(jq -r .n <<< "$JWK")")
e = INTEGER:0x$(b64url_hex "$(jq -r .e <<< "$JWK")")
CONF
openssl asn1parse -genconf "$WORK/key.conf" -noout -out "$WORK/key.der"
openssl pkey -pubin -inform DER -in "$WORK/key.der" -out "$WORK/key.pem"
printf '%s' "$HEADER.$PAYLOAD" > "$WORK/signed"
b64url_decode "$SIGNATURE" > "$WORK/signature"
# RS256 の署名は、鍵(n)と同じ長さのバイト列。余分な文字が付いたものは、ここで弾く
[[ $(wc -c < "$WORK/signature") -eq $(b64url_decode "$(jq -r .n <<< "$JWK")" | wc -c) ]] \
|| ng "署名の長さが鍵と合いません(中身が書き換えられています)"
openssl dgst -sha256 -verify "$WORK/key.pem" -signature "$WORK/signature" "$WORK/signed" > /dev/null 2>&1 \
|| ng "署名が合いません(中身が書き換えられています)"
# 3. 署名が正しいと分かったので、中身(iss と exp)を信じて確かめる
CLAIMS=$(b64url_decode "$PAYLOAD")
[[ $(jq -r .iss <<< "$CLAIMS") == "$ISSUER" ]] || ng "iss が自分の User Pool ではありません($(jq -r .iss <<< "$CLAIMS"))"
(( $(jq -r .exp <<< "$CLAIMS") > $(date +%s) )) || ng "有効期限(exp)を過ぎています"
echo "OK: 署名と iss と exp を確かめました"
jq --arg kid "$KID" '{ kid: $kid, token_use, sub }' <<< "$CLAIMS"
ターミナルウィンドウ
bash scripts/verify-jwt.sh "$(jq -r .AccessToken .tokens.json)"
# OK: 署名と iss と exp を確かめました

ペイロードの cognito:groups に root を足したトークンを作って、同じように確かめます。

ターミナルウィンドウ
TAMPERED=$(jq -r '
.AccessToken | split(".")
| .[1] |= (gsub("-"; "+") | gsub("_"; "/") | @base64d | fromjson
| .["cognito:groups"] += ["root"]
| tojson | @base64 | gsub("\\+"; "-") | gsub("/"; "_") | gsub("="; ""))
| join(".")' .tokens.json)
bash scripts/decode-jwt.sh "$TAMPERED" # cognito:groups が ["admin", "root"] になっている
bash scripts/verify-jwt.sh "$TAMPERED"
# NG: 署名が合いません(中身が書き換えられています)

真ん中(ペイロード)を開き、cognito:groups に root を足して、また base64url に戻しています。ヘッダーと署名はそのままです。

中身を 1 文字でも変えると署名が合わなくなります。API が「トークンの中身を信じてよい」のは、この確認を通したときだけです。

ターミナルウィンドウ
OTHER=$(aws cognito-idp create-user-pool --pool-name other --query UserPool.Id --output text)
POOL_ID=$OTHER bash scripts/verify-jwt.sh "$(jq -r .AccessToken .tokens.json)"
# NG: JWKS に kid が ap-northeast-1_xxxxxxxxx の鍵がありません

Floci は User Pool ごとに別の鍵を使います(本物も同じです)。別の User Pool の鍵では確かめられません。

scripts/refresh.sh は、.tokens.json のリフレッシュトークンを jq で取り出し、REFRESH_TOKEN_AUTH で送ります。

リフレッシュトークンで新しいトークンをもらう

scripts/refresh.sh
#!/usr/bin/env bash
# .tokens.json のリフレッシュトークンで、新しい ID / アクセストークンをもらう。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
REFRESH_TOKEN=$(jq -r .RefreshToken .tokens.json)
aws cognito-idp initiate-auth \
--client-id "$CLIENT_ID" \
--auth-flow REFRESH_TOKEN_AUTH \
--auth-parameters "REFRESH_TOKEN=$REFRESH_TOKEN" \
--query 'AuthenticationResult.{ExpiresIn:ExpiresIn,HasIdToken:IdToken!=null,HasRefreshToken:RefreshToken!=null}'
ターミナルウィンドウ
bash scripts/refresh.sh
{ "ExpiresIn": 3600, "HasIdToken": true, "HasRefreshToken": false }

新しい ID トークンとアクセストークンが返ります。リフレッシュトークンは返りません。手元のリフレッシュトークンを、期限まで使い続けます。

サインアウトしても、トークンの署名は正しいまま

Section titled “サインアウトしても、トークンの署名は正しいまま”
ターミナルウィンドウ
AT=$(jq -r .AccessToken .tokens.json)
aws cognito-idp global-sign-out --access-token "$AT"
aws cognito-idp get-user --access-token "$AT" # NotAuthorizedException: Access Token has been revoked
bash scripts/verify-jwt.sh "$AT" # OK: 署名と iss と exp を確かめました

Cognito に問い合わせれば「取り消し済み」と分かりますが、JWKS で署名を確かめるだけの API には分かりません。JWT は API が Cognito に問い合わせずに済むことと引き換えに、期限までは使えてしまいます。アクセストークンの有効期限を短めにするのはこのためです。

このセクションで見つけた違いをまとめます。

項目 Floci 2.4.0 本物の Cognito
iss のホスト http://localhost:4566 https://cognito-idp.<region>.amazonaws.com
確認メール 送らずに SES にためる(/_aws/ses) 実際に送る(送信数に上限がある)
存在しないユーザーでログイン PreventUserExistenceErrors を無視し、いつも UserNotFoundException ENABLED なら NotAuthorizedException(存在を漏らさない)。既定はコンソールで作ると ENABLED、API・CLI で値を渡さないと LEGACY(UserNotFoundException)
Lambda トリガー Floci は Lambda をコンテナで動かすので、コンテナエンジンへの接続が要る(このハンズオンでは試していない) 動く

後のセクションで見つけた違いも、ここにまとめておきます。

項目 Floci 2.4.0 本物の Cognito 見つけた所
確認コードの照合 AutoVerifiedAttributes に email が無いと、どんなコードでも確認が通る 違うコードは CodeMismatchException 05-01
どこから呼んでも iss いつも http://localhost:4566/<プール ID>。コンテナの中から floci:4566 で呼んでも変わらない いつも https://cognito-idp.<region>.amazonaws.com/<プール ID> このレクチャー
ブラウザから Cognito の API を呼ぶ FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS で CORS を許す必要がある 最初から CORS に対応している 03-01
存在しないユーザーでのログイン PreventUserExistenceErrors: ENABLED でも UserNotFoundException ENABLED ならパスワード違いと同じ NotAuthorizedException 03-04
外部 IdP から入ったユーザーの名前 EntraID_<別の UUID>。identities の userId とは違う値 EntraID_<IdP の sub>(identities の userId と同じ) 04-04
外部 IdP(OIDC)の登録 discovery を読みに行かないので、エンドポイントを全部明示する oidc_issuer だけでよく、discovery が届かないと登録を拒否する 04-04

それ以外の、このセクションで試したこと(パスワードポリシー、確認コードの照合、SECRET_HASH、許可していない認証フロー、グループ、署名、更新、サインアウト)は本物と同じ振る舞いでした。

このレクチャーでは、Floci に残るもの(User Pool・ユーザー・グループ)を新しく作っていません。作ったのは手元の道具だけなので、setup.sh に足す行はありません。

このレクチャーを終えた 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
# .tokens.json のリフレッシュトークンで、新しい ID / アクセストークンをもらう。
set -euo pipefail
cd "$(dirname "$0")/.."
source ./env.sh
source ./.cognito.env
REFRESH_TOKEN=$(jq -r .RefreshToken .tokens.json)
aws cognito-idp initiate-auth \
--client-id "$CLIENT_ID" \
--auth-flow REFRESH_TOKEN_AUTH \
--auth-parameters "REFRESH_TOKEN=$REFRESH_TOKEN" \
--query 'AuthenticationResult.{ExpiresIn:ExpiresIn,HasIdToken:IdToken!=null,HasRefreshToken:RefreshToken!=null}'
#!/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}'
#!/usr/bin/env bash
# JWKS を取ってきて、JWT の署名・発行者・有効期限を確かめる。
# 使い方: bash scripts/verify-jwt.sh <token>
# 別の User Pool で確かめたいときは POOL_ID=<プール ID> を付けて実行する(付けた値が .cognito.env より優先)
set -euo pipefail
cd "$(dirname "$0")/.."
GIVEN_POOL_ID=${POOL_ID:-}
source ./env.sh
source ./.cognito.env
POOL_ID=${GIVEN_POOL_ID:-$POOL_ID}
TOKEN=${1:?使い方: bash scripts/verify-jwt.sh <トークン>}
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
ng() { echo "NG: $*" >&2; exit 1; }
# base64url → バイト列。+ と / に戻し、= で 4 の倍数の長さにそろえてから戻す
b64url_decode() {
local s
s=$(printf '%s' "$1" | tr '_-' '/+')
while (( ${#s} % 4 )); do s+='='; done
printf '%s' "$s" | openssl base64 -d -A
}
# base64url → 16 進の文字列(鍵の数を openssl に渡すため)
b64url_hex() { b64url_decode "$1" | od -An -v -tx1 | tr -d ' \n'; }
# base64url の文字(A-Z a-z 0-9 - _)だけでできた 3 つの部分か。= や空白が混ざったものは受け付けない
[[ $TOKEN =~ ^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$ ]] \
|| ng "JWT の形(ヘッダー.ペイロード.署名)になっていません"
IFS=. read -r HEADER PAYLOAD SIGNATURE <<< "$TOKEN"
# Floci の iss は http://localhost:4566/<プール ID>。本物なら https://cognito-idp.<region>.amazonaws.com/<プール ID>
# トークンの中の iss ではなく、自分の User Pool から組み立てる
ISSUER="$AWS_ENDPOINT_URL/$POOL_ID"
# 1. 鍵を選ぶ。鍵の在りかは discovery(<iss>/.well-known/openid-configuration)が教えてくれる
JWKS_URI=$(curl -fsS "$ISSUER/.well-known/openid-configuration" | jq -r .jwks_uri) \
|| ng "discovery を読めませんでした($ISSUER)"
ALG=$(b64url_decode "$HEADER" | jq -r .alg)
KID=$(b64url_decode "$HEADER" | jq -r .kid)
[[ $ALG == RS256 ]] || ng "alg が RS256 ではありません($ALG)"
JWK=$(curl -fsS "$JWKS_URI" | jq -c --arg kid "$KID" '.keys[] | select(.kid == $kid)')
[[ -n $JWK ]] || ng "JWKS に kid が $KID の鍵がありません"
# 2. 署名を確かめる。JWK(n と e)から openssl が読める公開鍵(PEM)を組み立て、
# 「ヘッダー.ペイロード」の SHA-256 と署名が合うかを見る
cat > "$WORK/key.conf" <<CONF
asn1 = SEQUENCE:public_key
[public_key]
algorithm = SEQUENCE:rsa_algorithm
key = BITWRAP,SEQUENCE:rsa_key
[rsa_algorithm]
oid = OID:rsaEncryption
parameters = NULL
[rsa_key]
n = INTEGER:0x$(b64url_hex "$(jq -r .n <<< "$JWK")")
e = INTEGER:0x$(b64url_hex "$(jq -r .e <<< "$JWK")")
CONF
openssl asn1parse -genconf "$WORK/key.conf" -noout -out "$WORK/key.der"
openssl pkey -pubin -inform DER -in "$WORK/key.der" -out "$WORK/key.pem"
printf '%s' "$HEADER.$PAYLOAD" > "$WORK/signed"
b64url_decode "$SIGNATURE" > "$WORK/signature"
# RS256 の署名は、鍵(n)と同じ長さのバイト列。余分な文字が付いたものは、ここで弾く
[[ $(wc -c < "$WORK/signature") -eq $(b64url_decode "$(jq -r .n <<< "$JWK")" | wc -c) ]] \
|| ng "署名の長さが鍵と合いません(中身が書き換えられています)"
openssl dgst -sha256 -verify "$WORK/key.pem" -signature "$WORK/signature" "$WORK/signed" > /dev/null 2>&1 \
|| ng "署名が合いません(中身が書き換えられています)"
# 3. 署名が正しいと分かったので、中身(iss と exp)を信じて確かめる
CLAIMS=$(b64url_decode "$PAYLOAD")
[[ $(jq -r .iss <<< "$CLAIMS") == "$ISSUER" ]] || ng "iss が自分の User Pool ではありません($(jq -r .iss <<< "$CLAIMS"))"
(( $(jq -r .exp <<< "$CLAIMS") > $(date +%s) )) || ng "有効期限(exp)を過ぎています"
echo "OK: 署名と iss と exp を確かめました"
jq --arg kid "$KID" '{ kid: $kid, token_use, sub }' <<< "$CLAIMS"
.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=""
本番の API でも、このように自分で確かめるのですか?

いいえ。このスクリプトは、署名の確かめで何が起きているかを目で追うためのものです。本番の API では、aws-jwt-verify(AWS の公式)や jose などのライブラリを使ってください。

  • 取った鍵を覚えておき、知らない kid のトークンが来たときだけ JWKS を取り直します。このスクリプトのように毎回取りに行くと遅くなります
  • alg・iss・exp のほか、token_use・client_id(aud)や、発行前の時刻(nbf)なども漏れなく確かめます
鍵の取得先は iss から決めてよいのですか?

決め打ちしてよいのは、iss を自分の User Pool と照らし合わせたあとです。トークンの中の iss をそのまま信じて鍵を取りに行くと、攻撃者が自分の鍵の在りかを書いたトークンを送ってくるかもしれません。このスクリプトは、自分の User Pool の iss を先に組み立て、そこから鍵を取りに行っています。