コンテンツにスキップ

トークンが無いと作れないようにする

05 章 トークンが無いと作れないようにする

ノートの作成に、正しいアクセストークンを求めます。トークンが無い・正しくないときは 401 にします。

curl が POST /notes を呼ぶと、API の verifyToken() が Floci の公開鍵(JWKS)でトークンを確かめ、無い・正しくなければ 401、正しければ 201 になる

トークンの確認には、AWS が公開している aws-jwt-verify を使います。

ターミナルウィンドウ
cd apps/api
npm install aws-jwt-verify
cd ../..
apps/api/package.json
25
25
"@nestjs/common": "^12.0.1",
26
26
"@nestjs/core": "^12.0.1",
27
27
"@nestjs/platform-express": "^12.0.1",
28
"aws-jwt-verify": "^5.2.1",
28
29
"reflect-metadata": "^0.2.2",
29
30
"rxjs": "^7.8.1"
30
31
},

トークンを確かめる関数を作る

Section titled “トークンを確かめる関数を作る”

apps/api/src/auth/verify-token.ts を作成する

Section titled “apps/api/src/auth/verify-token.ts を作成する”
apps/api/src/auth/verify-token.ts
1
import { UnauthorizedException } from '@nestjs/common';
2
import { JwtVerifier } from 'aws-jwt-verify';
3
import { SimpleJwksCache } from 'aws-jwt-verify/jwk';
4
import type { CognitoAccessTokenPayload } from 'aws-jwt-verify/jwt-model';
5
6
// トークンの発行元(iss)。Floci の中の、自分のユーザープール
7
const issuer = `http://floci:4566/${process.env.COGNITO_USER_POOL_ID}`;
8
9
const verifier = JwtVerifier.create(
10
{
11
issuer,
12
// 署名を確かめる公開鍵(JWKS)の場所
13
jwksUri: `${issuer}/.well-known/jwks.json`,
14
// Cognito のアクセストークンには aud が無いので、代わりに token_use と client_id を確かめる
15
audience: null,
16
customJwtCheck: ({ payload }) => {
17
if (payload.token_use !== 'access') {
18
throw new Error('Not an access token');
19
}
20
if (payload.client_id !== process.env.COGNITO_CLIENT_ID) {
21
throw new Error('Wrong client');
22
}
23
},
24
},
25
{
26
// aws-jwt-verify は https でしか JWKS を取りに行かないので、http の Floci から fetch で取る
27
jwksCache: new SimpleJwksCache({
28
fetcher: { fetch: async (uri) => (await fetch(uri)).arrayBuffer() },
29
}),
30
},
31
);
32
33
/**
34
* Authorization ヘッダー(Bearer <アクセストークン>)を確かめ、正しければトークンの中身を返す。
35
* トークンが無い・正しくないときは 401 にする。
36
*/
37
export async function verifyToken(
38
authorization: string | undefined,
39
): Promise<CognitoAccessTokenPayload> {
40
const [type, token] = authorization?.split(' ') ?? [];
41
if (type !== 'Bearer' || !token) {
42
throw new UnauthorizedException('Missing bearer token');
43
}
44
try {
45
// 署名・発行元・有効期限と、上の customJwtCheck を確かめる
46
return (await verifier.verify(token)) as CognitoAccessTokenPayload;
47
} catch {
48
throw new UnauthorizedException('Invalid token');
49
}
50
}
  • issuer … トークンの発行元です。Floci の中の、自分のユーザープールです
  • audience: null と customJwtCheck … Cognito のアクセストークンには aud が無いので、代わりに token_use と client_id を確かめます
  • jwksCache … aws-jwt-verify は https でしか公開鍵(JWKS)を取りに行かないので、http の Floci から fetch で取ります

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

Section titled “apps/api/src/notes/notes.controller.ts を変更する”
apps/api/src/notes/notes.controller.ts
3
3
Controller,
4
4
Delete,
5
5
Get,
6
Headers,
6
7
HttpCode,
7
8
NotFoundException,
8
9
Param,
9
10
Post,
10
11
} from '@nestjs/common';
11
12
import { randomUUID } from 'node:crypto';
13
import { verifyToken } from '../auth/verify-token.js';
12
14
import { openDatabase } from '../database.js';
13
15
14
16
type Note = {
apps/api/src/notes/notes.controller.ts
26
28
private readonly db = openDatabase();
27
29
28
30
@Post()
29
create(@Body() input: { title: string; body?: string }): Note {
31
async create(
32
@Headers('authorization') authorization: string | undefined,
33
@Body() input: { title: string; body?: string },
34
): Promise<Note> {
35
// 正しいアクセストークンが無ければ、ここで 401 になる
36
await verifyToken(authorization);
30
37
const now = new Date().toISOString();
31
38
const note: Note = {
32
39
id: randomUUID(),
  • @Headers('authorization') … Authorization ヘッダーの値を受け取ります
  • await verifyToken(authorization) … 正しくなければ 401 の例外を投げるので、ノートは作られません
ターミナルウィンドウ
podman compose up -d --build --wait
curl -i -X POST http://localhost:3001/notes -H 'Content-Type: application/json' -d '{"title": "買い物", "body": "牛乳を買う"}'

1 行目が HTTP/1.1 401 Unauthorized で、最後の行が次のようになれば大丈夫です。

{"message":"Missing bearer token","error":"Unauthorized","statusCode":401}

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

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

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