コンテンツにスキップ

Entra ID にあるユーザーで Cognito にログイン

Entra ID にあるユーザーで Cognito にログイン

entra-local を Cognito の外部 IdP(OIDC)として登録し、ログインの画面の「Entra ID でログイン」で Entra のユーザーをアプリに入れます。仕組みは 03-05 で説明した Hosted UI(認可コードフロー)の上に乗っていて、Cognito のログイン画面の代わりに Entra のサインイン画面に回ります。気をつけるのは Entra に特有の部分、とくに ユーザーを何で見分けるか です。

このレクチャーで足す・変えるファイルは次のとおりです。

ファイル役割
作成public/lib/hosted-ui.jsHosted UI の仕組み(認可コード + PKCE・コールバック・ログアウト)
変更public/home.jsログイン中の画面の動き
変更public/index.htmlトップの画面。各画面へのリンク。04-04 で Entra ID から戻ってくる受け口にもなる
変更public/index.jsトップの画面の動き
変更public/login.htmlパスワードでログインする画面。04-04 で Entra ID のボタンが増える
変更public/login.jsログインの動き

handson/ で作業します。Floci を止めていたときは、起動してから bash scripts/setup.sh で前のレクチャーを終えた状態を作り直します(entra-local のアプリとユーザーはボリュームに残っています)。04-02 で控えた .entra.env も読み込みます。

ターミナルウィンドウ
podman compose up -d
curl -s http://localhost:8443/health # "status":"ok" が返ってから次へ(entra-local は起動に数秒かかる)
bash scripts/setup.sh # 前のレクチャーまでに作ったものを作り直す
source ./env.sh && source ./.cognito.env && source ./.entra.env

前のレクチャーで見たとおり、Entra の sub はアプリごとに変わります。本物の Cognito のユーザー名 EntraID_<sub> も、Entra にとっての「Cognito というアプリ」向けの値です。あとで別のアプリから同じ人を探したくなったとき、sub では見つかりません。

そこで、テナントの中で変わらない oid を、Cognito のカスタム属性 custom:entra_oid に持ち込みます。まず、02-02 で作った User Pool にカスタム属性を足します。

ターミナルウィンドウ
aws cognito-idp add-custom-attributes --user-pool-id "$POOL_ID" \
--custom-attributes Name=entra_oid,AttributeDataType=String,Mutable=true

entra-local を、User Pool の外部 IdP(OIDC)として登録します。名前は EntraID にします(画面はこの名前で呼び出します)。

ターミナルウィンドウ
aws cognito-idp create-identity-provider \
--user-pool-id "$POOL_ID" \
--provider-name EntraID \
--provider-type OIDC \
--provider-details "client_id=$ENTRA_CLIENT_ID,client_secret=$ENTRA_CLIENT_SECRET,
authorize_scopes=openid email profile,
oidc_issuer=http://localhost:8443/$ENTRA_TENANT_ID/v2.0,attributes_request_method=GET,
authorize_url=http://localhost:8443/$ENTRA_TENANT_ID/oauth2/v2.0/authorize,
token_url=http://entra-local:8443/$ENTRA_TENANT_ID/oauth2/v2.0/token,
attributes_url=http://entra-local:8443/graph/oidc/userinfo,
jwks_uri=http://entra-local:8443/$ENTRA_TENANT_ID/discovery/v2.0/keys" \
--attribute-mapping email=email,name=name,preferred_username=preferred_username,custom:entra_oid=oid,username=sub
オプション 設定する値 意味
--user-pool-id "$POOL_ID" どの User Pool に登録するか
--provider-name EntraID IdP の名前。画面はこの名前で呼び出す
--provider-type OIDC OpenID Connect の IdP として登録する
--provider-details (下の表) IdP につなぐための値
--attribute-mapping (下の表) Entra のクレームを、Cognito のどの属性に入れるか

--provider-details の中身:

項目 設定する値 意味
client_id $ENTRA_CLIENT_ID 04-02 で登録したアプリのクライアント ID
client_secret $ENTRA_CLIENT_SECRET 04-02 で作ったシークレット
authorize_scopes openid email profile Entra に求めるスコープ
oidc_issuer http://localhost:8443/$ENTRA_TENANT_ID/v2.0 Entra の issuer。v2.0 の、自分のテナントのもの にする(common ではない)
attributes_request_method GET userinfo を GET で呼ぶ
authorize_url http://localhost:8443/... サインインの画面。ブラウザが開く ので localhost
token_url http://entra-local:8443/... トークンのエンドポイント。Floci がコンテナの中から呼ぶ ので、サービス名 entra-local(コンテナの中から見ると localhost は Floci 自身)
attributes_url http://entra-local:8443/graph/oidc/userinfo userinfo。Floci が呼ぶので entra-local
jwks_uri http://entra-local:8443/.../discovery/v2.0/keys トークンの署名を確かめる鍵。Floci が呼ぶので entra-local

本物の Cognito なら oidc_issuer だけで、ほかのエンドポイントは discovery から読みます。Floci は discovery を読まないので、全部書きます。

--attribute-mapping の中身(Cognito の属性=Entra のクレーム):

Cognito の属性 Entra のクレーム 意味
email email メールアドレス
name name 表示名
preferred_username preferred_username サインインに使う名前(UPN)
custom:entra_oid oid 上で足したカスタム属性に、変わらない oid を入れる
username sub Cognito のユーザー名の元にする値

Entra ID でのログインは、03-05 で説明した Hosted UI の仕組み(認可コードフロー)の上に乗っています。02-03 で作った App Client は、パスワードを受け取るログイン(USER_PASSWORD_AUTH)だけを許しているので、認可コードフロー・戻ってよい先(コールバック URL)・使ってよい IdP(EntraID)を足します。

ターミナルウィンドウ
aws cognito-idp update-user-pool-client \
--user-pool-id "$POOL_ID" --client-id "$CLIENT_ID" \
--explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \
--prevent-user-existence-errors ENABLED \
--supported-identity-providers COGNITO EntraID \
--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 \
--read-attributes email email_verified name preferred_username custom:entra_oid \
--query 'UserPoolClient.{IdPs:SupportedIdentityProviders,Callback:CallbackURLs,Flows:AllowedOAuthFlows}'
オプション 設定する値 意味
--user-pool-id / --client-id "$POOL_ID" / "$CLIENT_ID" どの App Client を変えるか
--explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH 今の設定(パスワードでのログインと更新)。渡し直さないと消える
--prevent-user-existence-errors ENABLED 今の設定。渡し直さないと既定値に戻る
--supported-identity-providers COGNITO EntraID 使ってよい IdP。COGNITO は User Pool 自身のユーザー、EntraID は上で登録した Entra ID
--callback-urls http://localhost:3000/ ログインのあとに戻ってよい先。ここに無い URL へは戻さない(認可コードを盗まれないため)
--logout-urls http://localhost:3000/ ログアウトのあとに戻ってよい先
--allowed-o-auth-flows code 認可コードフローを許す
--allowed-o-auth-scopes openid email profile 渡してよいスコープ。ID トークンにメールや名前を載せる
--allowed-o-auth-flows-user-pool-client (値なし) この App Client で、上の OAuth の設定を使うことを有効にする
--read-attributes email email_verified name preferred_username custom:entra_oid アプリがトークンで読める属性。custom:entra_oid を入れておかないと、トークンに載らない
--query UserPoolClient.{IdPs:...,Callback:...,Flows:...} 応答のうち、変えた所だけを出す

「Entra ID でログイン」を押してから戻ってくるまでに、次のことが起きています(開発者ツールの Network タブで追えます)。

  1. 画面が code_verifier(ランダムな文字列)を作り、そのハッシュ code_challenge を付けて /oauth2/authorize へ移る
  2. Cognito が Entra ID のサインイン画面へ回し、ユーザーが Entra のパスワードを入れる
  3. Cognito が 認可コード を付けて、登録された戻り先(http://localhost:3000/?code=...)へ戻す
  4. 画面が認可コードと code_verifier を /oauth2/token に送り、トークンを受け取る

認可コードは URL に載るので、横取りされるかもしれません。PKCE では、最初に送ったハッシュの元(code_verifier)を知っている人しかコードをトークンに換えられません。Floci も、code_verifier が合わないと invalid_grant を返します。

この流れを、ライブラリなしで書いた public/lib/hosted-ui.js と、「Entra ID でログイン」のボタンを足した画面を置きます。

ファイル役割
public/confirm.htmlメールに届いた確認コードを入れる画面
public/confirm.js確認コードの動き
public/home.htmlログイン中の画面。ID トークンの中身とログアウト
変更public/home.jsログイン中の画面の動き
変更public/index.htmlトップの画面。各画面へのリンク。04-04 で Entra ID から戻ってくる受け口にもなる
変更public/index.jsトップの画面の動き
public/lib/cognito.jsAWS SDK を CDN から読み込み、Floci に向けた client を用意する
public/lib/config.jsconfig.json を読み、Cognito の API の入口を求める
public/lib/form.jsフォームの値を読み、メッセージやエラーを出す
作成public/lib/hosted-ui.jsHosted UI の仕組み(認可コード + PKCE・コールバック・ログアウト)
public/lib/tokens.jsトークンの保存・読み出し・中身を読む
変更public/login.htmlパスワードでログインする画面。04-04 で Entra ID のボタンが増える
変更public/login.jsログインの動き
public/mail.htmlFloci に届いたメールを読むメールボックス
public/mail.jsメールボックスの動き
public/signup.htmlサインアップの画面
public/signup.jsサインアップの動き
public/style.cssどの画面でも使う見た目

上のボタンで、このレクチャーを終えた public/ をダウンロードし、handson/ の中で展開して上書きします(public/config.json はそのまま残ります)。hosted-ui.js の要は次のところです。

public/lib/hosted-ui.js22〜41 行目

const verifier = randomString();
const challenge = base64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
const state = randomString();
// ...
const params = {
client_id: config.clientId,
response_type: 'code',
redirect_uri: redirectUri,
scope: 'openid email profile',
state,
code_challenge: challenge,
code_challenge_method: 'S256',
};
// ...
const url = new URL(discovery.authorization_endpoint);
url.search = new URLSearchParams(params);
location.assign(url);

認可・トークンのエンドポイントは、User Pool の discovery(<iss>/.well-known/openid-configuration)から読んでいます。Floci では http://localhost:4566/cognito-idp/oauth2/authorize、本物では https://<ドメイン>.auth.<リージョン>.amazoncognito.com/oauth2/authorize です。

トークンエンドポイントの応答は id_token のような snake_case なので、パスワードでログインしたときと同じ形(idToken)にそろえて保存します。こうしておくと、ログイン中の画面(home.html)は 03-04 のまま使えます。

  • hostedLogin('EntraID') … identity_provider=EntraID(register-entra.sh の --provider-name)を付けて /oauth2/authorize へ移ります。Cognito は自分のログイン画面を飛ばして、Entra のサインイン画面へ直行します
  • handleCallback() … 戻ってきた ?code=... を code_verifier と一緒に /oauth2/token へ送り、トークンを保存します
  • hostedLogout() … Cognito の /logout に移り、Hosted UI 側のログイン状態(Cookie)も消します

画面の変わったところは次のとおりです。

  • login.html・login.js … 「Entra ID でログイン」のボタン。押すと hostedLogin('EntraID') を呼びます
  • index.js … Entra ID から戻ってくる先(コールバック URL)はトップ(http://localhost:3000/)です。トップで handleCallback() を呼んで認可コードをトークンに換え、ログイン中の画面へ移ります
  • home.js … ログアウトでは、手元のトークンを消したあと、hostedLogout() で Cognito の /logout にも移ります

http://localhost:3000 の「ログイン」を開き(開いていたら読み込み直し)、「Entra ID でログイン」を押します。entra-local のサインイン画面で taro@entralocal.dev / Passw0rd! を入れます。トップに戻り、ログイン中の画面に移ったら、ID トークンを見てください。

開発者ツールの Network タブでは、localhost:3000 → localhost:4566/.../oauth2/authorize → localhost:8443/.../authorize(Entra)→ localhost:4566/.../oauth2/idpresponse → localhost:3000/?code=... と移るのが見えます。Entra のトークンを受け取るのは Cognito で、画面が受け取るのは Cognito のトークン です。

{
"cognito:username": "EntraID_272c8101-ef40-41cb-bd40-ed64f04a6546",
"custom:entra_oid": "daa6ae20-6153-4193-a9f7-9f8cc48bbf34",
"name": "山田 太郎",
"preferred_username": "taro@entralocal.dev",
"email": "taro@entralocal.dev",
"iss": "http://localhost:4566/ap-northeast-1_16130330b"
}

Cognito のユーザーの一覧で、Entra から入ったユーザーに custom:entra_oid が入っているかを見ます。

ターミナルウィンドウ
aws cognito-idp list-users --user-pool-id "$POOL_ID" \
--query 'Users[].{Username:Username,Email:Attributes[?Name==`email`]|[0].Value,EntraOid:Attributes[?Name==`custom:entra_oid`]|[0].Value}' \
--output table
| Email | EntraOid | Username |
| carol@example.com | None | carol |
| taro@entralocal.dev| daa6ae20-6153-4193-a9f7-9f8cc48bbf34 | EntraID_272c8101-ef40-41cb-bd40-ed64f04a6546 |

本物の Entra ID につなぐときに踏みやすいところです。entra-local で再現できるものと、できないものがあります。

  • テナントごとの issuer と common … https://login.microsoftonline.com/<テナント ID>/v2.0 が issuer です。common や organizations のエンドポイントで発行されたトークンも、iss には個々のテナント ID が入ります。Cognito に登録する oidc_issuer は自分のテナントのものにします
  • email が来ないことがある … Entra の email は、ユーザーにメールアドレスが設定されていないと入りません。必ずある preferred_username(UPN)と混同しないこと。Cognito の属性で email を必須にしていると、ログインに失敗する人が出ます
  • email で人を結び付けない … Entra の email は、ユーザーやテナントの管理者が設定できる値で、そのアドレスを持っていることは確かめられていません。Cognito でも、外部 IdP から入れた email は既定で未確認の扱いです。既存のユーザーとの結び付け(AdminLinkProviderForUser など)や、アプリでの人の特定には email を使わず、oid(と tid)か Cognito の sub を使ってください。別人のアドレスを名乗った Entra のユーザーに、アカウントを乗っ取られるおそれがあります
  • グループの overage … groups クレームを有効にしても、所属が多い(ID トークンで 200 を超える)ユーザーでは一覧の代わりに「Graph で引いてください」という印(_claim_names)が入ります。entra-local でも groupOverageLimit で再現できます
  • シークレットの期限切れ … Entra のクライアントシークレットには期限があります(既定は 6 か月〜2 年)。切れると Cognito からのトークン交換が失敗し、全員がログインできなくなります。期限を管理しておくこと

このレクチャーを終えた 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
# Floci のデータはメモリにあり、止めると消える。ここまでのレクチャーで作ったものを、順に作り直す。
# レクチャーを 1 つ終えるたびに、そのレクチャーで作ったものを 1 行ずつ足していく。
set -euo pipefail
cd "$(dirname "$0")/.."
bash scripts/create-user-pool.sh
.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=""
entra-local のサインイン画面で「Invalid redirect URI」と出ます

アプリの登録のリダイレクト URI と、Cognito(Floci)が送ってくる redirect_uri(http://localhost:4566/cognito-idp/oauth2/idpresponse)が 1 文字でも違うと拒否されます。04-02 の手順でアプリを登録し直し、update-identity-provider で Cognito 側の登録も新しいクライアント ID とシークレットに合わせます。

ログアウトしたのに、「Entra ID でログイン」でパスワードを聞かれません

画面のログアウトが消すのは、手元のトークンと Cognito のログイン状態だけです。Entra 側のサインイン(entra-local の Cookie)は残っているので、Entra はそのまま Cognito に戻します。本物の Entra ID と Cognito でも同じで、Cognito の /logout は外部 IdP のログインを終わらせません。

別のユーザーで試したいときは、Entra のサインアウトの入口(discovery の end_session_endpoint)を開いてから、もう一度押してください。

http://localhost:8443/11111111-1111-1111-1111-111111111111/oauth2/v2.0/logout

本番で Entra からもサインアウトさせたいときは、Cognito の /logout のあとに、この入口(https://login.microsoftonline.com/<テナント ID>/oauth2/v2.0/logout)へ移します。

state は何のためにありますか?

ログイン画面から戻ってきた応答が、自分が出した要求への応答かを確かめるためです。別のサイトに仕込まれたリンクから、攻撃者の認可コードで戻されるのを防ぎます(CSRF 対策)。

Entra のアプリロールやグループで認可したいときは?

本物の Entra では、アプリロールをユーザーに割り当てると ID トークンの roles クレームに入ります。属性のマッピングでカスタム属性に持ち込めば、Cognito のトークンで読めます。entra-local もアプリロールの定義はできますが、ユーザーへの割り当てまではこのハンズオンでは試していません。