コンテンツにスキップ

コンテナの用意

コンテナの用意

Microsoft Entra ID(旧 Azure AD)を外部 IdP にする練習をします。本物の Entra テナントを使わず、手元で Entra ID を真似する entra-local を使います。

Entra ID はローカルで再現できるか

Section titled “Entra ID はローカルで再現できるか”

entra-local は、MSAL(Microsoft の認証ライブラリ)が話す OIDC / OAuth 2.0 の範囲を真似します。

再現できる 再現できない
discovery・JWKS・authorize・token・userinfo SAML 2.0(Cognito に SAML で登録する練習はできない)
認可コード(+ PKCE)・クライアントクレデンシャル・リフレッシュ・デバイスコード MFA・条件付きアクセス・同意画面
アプリの登録・シークレット・ユーザー・グループ マルチテナント(テナントは 1 つだけ)
tid・oid など Entra 特有のクレーム Graph API の大部分

本物と違う点もあります。entra-local の userinfo は oid を返しますが、本物の Entra の userinfo は返しません(oid は ID トークンにだけ入る)。

Cognito に OIDC で登録する練習には十分です。

このレクチャーでは、compose.yaml に entra-local を足して起動します。足す・変えるファイルは次のとおりです。

ファイル役割
変更compose.yamlコンテナの定義。Floci から始まり、03 で nginx、04 で entra-local が増える

compose.yaml に entra-local サービスと、データを残すボリュームを足します。設定の意味は下で説明します。

コンテナの定義。Floci から始まり、03 で nginx、04 で entra-local が増える色の付いた行が、このレクチャーで足す行です

compose.yaml
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:

podman compose up -d で、Floci はそのまま、entra-local が新しく起動します。

ターミナルウィンドウ
podman compose up -d

entra-local の health に問い合わせます。

ターミナルウィンドウ
curl -s http://localhost:8443/health

"status":"ok" が返れば起動しています。entra-local は起動に数秒かかるので、何も返らないときは、数秒待ってからもう一度打ってください。

起動したら、discovery(OIDC の設定の一覧)から、あとで Cognito に登録する値を見ます。

ターミナルウィンドウ
curl -s http://localhost:8443/11111111-1111-1111-1111-111111111111/v2.0/.well-known/openid-configuration \
| jq '{issuer, authorization_endpoint, token_endpoint, userinfo_endpoint, jwks_uri}'
{
"issuer": "http://localhost:8443/11111111-1111-1111-1111-111111111111/v2.0",
"authorization_endpoint": "http://localhost:8443/11111111-1111-1111-1111-111111111111/oauth2/v2.0/authorize",
"token_endpoint": "http://localhost:8443/11111111-1111-1111-1111-111111111111/oauth2/v2.0/token",
"userinfo_endpoint": "http://localhost:8443/graph/oidc/userinfo",
"jwks_uri": "http://localhost:8443/11111111-1111-1111-1111-111111111111/discovery/v2.0/keys"
}

11111111-... が テナント ID です。本物の Entra でも、URL の途中にテナント ID が入り、/v2.0 で終わる issuer になります。管理ポータルは http://localhost:8443/ で開けます。

テナント は、Entra ID の中の 1 つの組織(会社や学校など)の入れ物です。ユーザーやアプリの登録は、テナントの中に置かれます。テナント ID はその入れ物を見分ける GUID で、issuer やエンドポイントの URL の途中に入ります。

本物の Entra ID entra-local
テナント ID の決まり方 テナントを作ったときに Microsoft が割り当てる。自分では決められない 起動するときの設定で決まる。何も指定しないと 11111111-1111-1111-1111-111111111111
どこで見るか Microsoft Entra 管理センターの「概要」の「テナント ID」 curl -s http://localhost:8443/health の tenantId
テナントの数 組織ごとにいくつでもある 1 つだけ

1111... は entra-local の既定値で、このハンズオンではそのまま使います。変えたいときは、compose.yaml の entra-local の environment に TENANT_ID を足します。GUID の形(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)でないと、TENANT_ID: must be a GUID と出て起動しません。

TENANT_ID: 22222222-2222-2222-2222-222222222222

変えると、issuer やエンドポイントの URL も新しいテナント ID に変わり、1111... の URL は 404 になります。このハンズオンの本文やコマンドは 1111... で書いているので、変えたときは URL と、04-02 で .entra.env に書く ENTRA_TENANT_ID も合わせてください。

compose.yaml の entra-local の設定:

compose.yaml21〜29 行目

image: ghcr.io/cmaneu/entra-local:0.1.1
platform: linux/amd64
environment:
TLS_ENABLED: "false"
PUBLIC_ORIGIN: http://localhost:8443
REQUIRE_PASSWORD: "true"
  • platform: linux/amd64 … amd64 向けのイメージしか無いため。Apple Silicon の Mac ではエミュレーションで動き、起動に少し時間がかかります
  • TLS_ENABLED: "false" … entra-local は既定で自己署名証明書の HTTPS で動きます。04-04 で Floci がコンテナの中から entra-local を呼ぶとき、証明書を信頼させる手間を省くために HTTP にしています(本物の Entra は必ず HTTPS です)
  • REQUIRE_PASSWORD: "true" … 既定はアカウントを選ぶだけでサインインできます。本物に近づけるため、パスワードを求めます

Apple Silicon の Mac は、podman machine の仮想マシンに amd64 のエミュレーションが入っているので、そのまま動きます(手元では起動まで 10 秒ほど)。

ARM のパソコン(Raspberry Pi・ARM の VM・Windows on ARM の WSL2 など)では、amd64 のエミュレーションを先に入れないと exec format error で起動しません。x86_64(amd64)のパソコンなら、この手順は要りません。

ターミナルウィンドウ
sudo apt-get install -y qemu-user-static

1 分ほど待っても curl に何も返らないときは、podman compose logs entra-local でログを見てください。

このレクチャーを終えた 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 });
}
// ログインで受け取ったトークンを、どの画面からも読めるように保存する
// 練習なので 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';
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);
location.assign('./login.html');
});
<!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>
<script type="module" src="./index.js"></script>
</body>
</html>
import { cognitoEndpoint } from './lib/config.js';
document.querySelector('#endpoint').textContent = cognitoEndpoint;
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ログイン</title>
<link rel="stylesheet" href="./style.css">
</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>
<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';
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;
<!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
# Floci のデータはメモリにあり、止めると消える。ここまでのレクチャーで作ったものを、順に作り直す。
# レクチャーを 1 つ終えるたびに、そのレクチャーで作ったものを 1 行ずつ足していく。
set -euo pipefail
cd "$(dirname "$0")/.."
bash scripts/create-user-pool.sh
.cognito.env
public/config.json
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=""
HTTPS のまま使えませんか?

使えますが、Floci のコンテナに entra-local の自己署名証明書を信頼させる必要があります(このハンズオンでは試していません)。証明書は entra-local の管理ポータルの「Trust the certificate」からダウンロードできます。

データを消したいときは?

ユーザーやアプリ登録は、entra-local のデータボリュームに SQLite で残ります。podman compose down では消えません。消すときは podman compose down -v でボリュームごと消します。消したあとは、04-05 でスクリプトにしたあとなら podman compose up -d・bash scripts/setup.sh で作り直せます。それより前なら、04-02 から手順をやり直してください。