コンテンツにスキップ

役割で認可する

06 章 役割で認可する

役割 で認可します。Cognito の グループ admin に入っている人は、だれのノートでも消せるようにします。グループはアクセストークンの cognito:groups に入るので、API はトークンを見るだけで分かります。

admin がログインすると、Cognito(Floci)はグループ admin をトークンに入れる。API は cognito を見て、admin なら 204 で消せる

セットアップのスクリプトで、グループ admin と、そこに入れる管理者のユーザー admin@example.com を作ります。

apps/api/scripts/setup-cognito.js を変更する

Section titled “apps/api/scripts/setup-cognito.js を変更する”
apps/api/scripts/setup-cognito.js
36
36
ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],
37
37
});
38
38
39
// 管理者のグループ(admin)と、そこに入れる管理者のユーザー(admin@example.com)
40
await cognito('CreateGroup', { UserPoolId: UserPool.Id, GroupName: 'admin' });
41
await cognito('AdminCreateUser', {
42
UserPoolId: UserPool.Id,
43
Username: 'admin@example.com',
44
UserAttributes: [
45
{ Name: 'email', Value: 'admin@example.com' },
46
{ Name: 'email_verified', Value: 'true' },
47
],
48
MessageAction: 'SUPPRESS',
49
});
50
await cognito('AdminSetUserPassword', {
51
UserPoolId: UserPool.Id,
52
Username: 'admin@example.com',
53
Password: 'Passw0rd!',
54
Permanent: true,
55
});
56
await cognito('AdminAddUserToGroup', {
57
UserPoolId: UserPool.Id,
58
Username: 'admin@example.com',
59
GroupName: 'admin',
60
});
61
39
62
// API が読む設定(.env)
40
63
await writeFile(
41
64
'.env',
apps/api/scripts/setup-cognito.js
47
70
`${JSON.stringify({ issuer: `${endpoint}/${UserPool.Id}`, clientId: UserPoolClient.ClientId })}\n`,
48
71
);
49
72
console.log(
50
`ユーザープール ${UserPool.Id} とクライアント ${UserPoolClient.ClientId} を作り、.env と apps/ui/config.json に書きました`,
73
`ユーザープール ${UserPool.Id} とクライアント ${UserPoolClient.ClientId}、admin グループと admin@example.com を作り、.env と apps/ui/config.json に書きました`,
51
74
);
  • CreateGroup … グループを作ります
  • AdminCreateUser・AdminSetUserPassword … サインアップの画面を通さずにユーザーを作り、パスワードを決めます(MessageAction: 'SUPPRESS' で、招待のメールは送りません)
  • AdminAddUserToGroup … ユーザーをグループに入れます

apps/api/src/notes/notes.controller.ts を変更する

Section titled “apps/api/src/notes/notes.controller.ts を変更する”
apps/api/src/notes/notes.controller.ts
73
73
if (!note) {
74
74
throw new NotFoundException(`Note ${id} not found`);
75
75
}
76
// 作った人でなければ 403
77
if (note.ownerId !== user.sub) {
76
// admin グループの人は、だれのノートでも消せる
77
const isAdmin = user['cognito:groups']?.includes('admin') ?? false;
78
// 作った人でも admin でもなければ 403
79
if (note.ownerId !== user.sub && !isAdmin) {
78
80
throw new ForbiddenException();
79
81
}
80
82
this.db.prepare('DELETE FROM notes WHERE id = ?').run(id);
  • user['cognito:groups'] … トークンに入っているグループの配列です。グループに入っていない人には、この項目がありません

スクリプトを変えたので、Floci を起動し直して作り直します。Floci のユーザーは消えるので、alice と bob はサインアップし直します。

ターミナルウィンドウ
podman compose down
podman compose up -d --build --wait
node apps/api/scripts/setup-cognito.js
podman compose up -d --wait

http://localhost:3000/login.html で admin@example.com と Passw0rd! でログインし、出たアクセストークンの中身を見ます。

ターミナルウィンドウ
node -e "console.log(JSON.parse(Buffer.from(process.argv[1].split('.')[1], 'base64url')))" <アクセストークン>

'cognito:groups': [ 'admin' ] が入っていれば大丈夫です。

alice と bob をサインアップし直し、alice のトークンでノートを作ります。そのノートを、bob と admin のトークンで消します。

ターミナルウィンドウ
curl -i -X DELETE http://localhost:3001/notes/21a481a3-b808-4653-a833-89ffe6a9db37 -H 'Authorization: Bearer <bob のアクセストークン>'
curl -i -X DELETE http://localhost:3001/notes/21a481a3-b808-4653-a833-89ffe6a9db37 -H 'Authorization: Bearer <admin のアクセストークン>'

1 行目が、順に HTTP/1.1 403 Forbidden、HTTP/1.1 204 No Content になれば大丈夫です。

この節は、次の公式ドキュメントをもとに書いています。

この節を終えたときのディレクトリ

Section titled “この節を終えたときのディレクトリ”
この節を終えた状態をダウンロード