使用 Node.js 构建带 JWT 认证的 REST API
使用 NestJS 和 PostgreSQL,在 Node.js 和 TypeScript 中构建可用于生产环境的 JWT 认证 REST API:从单个文件一直到可部署的应用。
该 API 用于存储个人笔记。用户使用邮箱和密码注册,获取短期有效的 JWT 访问令牌和轮换刷新的刷新令牌,并且只能读写自己的笔记。每个构建块在本文档中都有对应章节;本教程按照真实项目所需的顺序把它们组合起来,并在你需要细节时链接到相应章节。
完成本教程后,这个 API 将能够:
- 使用 Zod schema 校验每个请求体、查询字符串和路由参数,同时为处理器提供类型。
- 使用
@nestjs/authentication实现用户登录:密码使用 scrypt 哈希,访问令牌使用 HS256,刷新令牌每次使用都轮换,并在某个令牌被重复使用时撤销整个令牌族。 - 通过 Drizzle 将用户、笔记和刷新令牌存储在 PostgreSQL 中。
- 配置缺失或格式错误时拒绝启动。
- 限制任何人猜测密码的速度。
- 每个响应都发送安全响应头,并且只接受来自你列出的来源的浏览器请求。
- 通过 OpenAPI 文档和 Swagger UI 描述自身。
- 响应存活和就绪检查,并在收到
SIGTERM时干净地关闭。 - 生产环境下以 JSON 格式写日志,并掩码密码和令牌。
- 无需数据库服务器即可运行端到端测试。
以下是各端点以及添加它们的小节:
| 端点 | 小节 |
|---|---|
GET /notes、GET /notes/:id、POST /notes、PATCH /notes/:id、DELETE /notes/:id |
从单个文件开始 |
POST /auth/sign-up、POST /auth/token、POST /auth/token/refresh、POST /auth/token/revoke、GET /me |
使用 JWT 登录用户 |
GET /docs |
使用 OpenAPI 描述 API |
GET /health/live、GET /health/ready |
添加健康检查 |
完成后的应用位于 GitHub:nestjs/example-rest-api-jwt-authentication,其中包含测试和 CI 工作流。
你需要 Node.js 22 或更高版本;从第二节开始还需要一个 PostgreSQL 服务器。
从单个文件开始
使用 Nest CLI 创建项目。--minimal 会生成一个代码集中在单个文件 src/main.ts 中的应用(参见单文件项目)。它还会安装 NestJS Observe SDK,即 @nestjs/observe,并将其接入该文件;应用自身的文件保持不变:
$ npm i -g @nestjs/cli
$ nest new notes-api --minimal
$ cd notes-api安装 Node 适配器 和 Zod。Node 适配器直接在 node:http 上运行 Nest,是三种适配器中最快的。CLI 安装的 Express 适配器已不再需要:
$ npm i --save @nestjs/platform-node zod
$ npm uninstall @nestjs/platform-express @types/express用 API 的第一个版本替换 src/main.ts。目前它把笔记保存在内存中:
import { randomUUID } from 'node:crypto';
import {
Body,
Controller,
Delete,
Get,
HttpCode,
Injectable,
NotFoundException,
Param,
Patch,
Post,
StandardSchemaValidationPipe,
} from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { createObserveModule } from '@nestjs/observe';
import { NodeAdapter } from '@nestjs/platform-node';
import { z } from 'zod';
const { ObserveModule, ObserveInstrument } = createObserveModule();
const title = z.string().trim().min(1).max(200);
const body = z.string().max(10_000);
const createNoteSchema = z.object({ title, body: body.default('') });
type CreateNoteDto = z.infer<typeof createNoteSchema>;
// 每个字段都可选,但都不允许 null:title 为 null 时返回 400。
const updateNoteSchema = z.object({ title, body }).partial();
type UpdateNoteDto = z.infer<typeof updateNoteSchema>;
interface Note {
id: string;
title: string;
body: string;
createdAt: Date;
updatedAt: Date;
}
@Injectable()
class NotesService {
private readonly notes = new Map<string, Note>();
findAll(): Note[] {
return [...this.notes.values()];
}
findOne(id: string): Note {
const note = this.notes.get(id);
if (!note) {
throw new NotFoundException();
}
return note;
}
create(dto: CreateNoteDto): Note {
const now = new Date();
const note: Note = { id: randomUUID(), ...dto, createdAt: now, updatedAt: now };
this.notes.set(note.id, note);
return note;
}
update(id: string, dto: UpdateNoteDto): Note {
const note = this.findOne(id);
Object.assign(note, dto, { updatedAt: new Date() });
return note;
}
remove(id: string): void {
if (!this.notes.delete(id)) {
throw new NotFoundException();
}
}
}
const noteId = { schema: z.uuid() };
@Controller('notes')
class NotesController {
constructor(private readonly notesService: NotesService) {}
@Get()
findAll() {
return this.notesService.findAll();
}
@Get(':id')
findOne(@Param('id', noteId) id: string) {
return this.notesService.findOne(id);
}
@Post()
create(@Body({ schema: createNoteSchema }) dto: CreateNoteDto) {
return this.notesService.create(dto);
}
@Patch(':id')
update(@Param('id', noteId) id: string, @Body({ schema: updateNoteSchema }) dto: UpdateNoteDto) {
return this.notesService.update(id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', noteId) id: string) {
this.notesService.remove(id);
}
}
const app = await NestFactory.create(
{
imports: [
ObserveModule.forRoot({
// 在 `npx @nestjs/observe link` 把密钥对写入 .env 之前保持为空;此时 SDK 不发送任何内容。
appKey: process.env.OBSERVE_APP_KEY ?? '',
appSecret: process.env.OBSERVE_APP_SECRET ?? '',
serviceId: 'notes-api',
}),
],
controllers: [NotesController],
providers: [NotesService],
},
new NodeAdapter(),
{ instrument: ObserveInstrument },
);
app.useGlobalPipes(new StandardSchemaValidationPipe());
await app.listen(process.env.PORT ?? 3000);- 这里没有模块类:
NestFactory.create()直接接收根模块的元数据(参见从元数据创建根模块)。下一节当应用需要导入自己的模块时,模块类会重新出现。使用适配器时,应用选项(包括instrument)是第三个参数。 StandardSchemaValidationPipe校验每个声明了schema的参数,支持 Zod 或任何其他 Standard Schema 库,并把 schema 的输出传给处理器,因此body默认为空字符串,title会被去除首尾空白。每个 schema 的推断类型就是参数类型,因此不需要维护同步的 DTO 类。参见基于 Schema 的校验。updateNoteSchema由相同的字段 schema 构建,而不是使用createNoteSchema.partial()。Zod 在partial()中仍然会应用默认值,因此一个只重命名笔记的PATCH请求会把body重置为空字符串。- 可选字段不允许为 null。带有
null标题的PATCH请求会得到 400,而不是触发数据库的NOT NULL约束并返回 500。
启动应用,并在另一个终端中尝试请求(--json 会发送一个带 JSON 请求体的 POST 请求,需要 curl 7.82 或更高版本):
$ npm run start:dev创建一条笔记,然后尝试几个会校验失败的请求:
$ curl localhost:3000/notes --json '{"title":"Buy milk"}'
{"id":"d90a31d3-2df2-447d-8d5e-c2b2e241a8eb","title":"Buy milk","body":"","createdAt":"2026-11-19T19:42:46.765Z","updatedAt":"2026-11-19T19:42:46.765Z"}
$ curl localhost:3000/notes --json '{"title":""}'
{"message":["title: Too small: expected string to have >=1 characters"],"error":"Bad Request","statusCode":400}
$ curl -X PATCH localhost:3000/notes/d90a31d3-2df2-447d-8d5e-c2b2e241a8eb --json '{"title":null}'
{"message":["title: Invalid input: expected string, received null"],"error":"Bad Request","statusCode":400}
$ curl localhost:3000/notes/not-a-uuid
{"message":["Invalid UUID"],"error":"Bad Request","statusCode":400}将笔记存储在 PostgreSQL 中
笔记会在每次重启时丢失。通过 @nestjs/drizzle 将它们迁移到 PostgreSQL,并使用 @nestjs/config 从环境变量读取数据库 URL:
$ npm i --save @nestjs/config @nestjs/drizzle drizzle-orm@rc pg
$ npm i --save-dev drizzle-kit@rc @types/pg本地数据库使用一个容器就足够了:
$ docker run -d --name notes-db -e POSTGRES_PASSWORD=notes -e POSTGRES_DB=notes -p 5432:5432 postgres:17把数据库 URL 添加到项目根目录的 .env 文件中。ConfigModule 会在启动时加载该文件,drizzle-kit 也会读取它:
DATABASE_URL=postgres://postgres:notes@localhost:5432/notes这个文件越来越长了,现在适合给它划分一些结构。每个部分都移动到 src/ 下自己的文件,根模块也重新变回一个类,因为它现在需要导入其他模块:
配置本身也是一个 Zod schema。ConfigModule 在启动时用它校验环境变量,并提供 schema 返回的值,因此 PORT 是数字:
import { z } from 'zod';
export const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
});
export type Env = z.infer<typeof envSchema>;下面是使用 Drizzle schema 语言定义的表:
import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });
export const notes = pgTable('notes', {
id: uuid('id').primaryKey().defaultRandom(),
title: text('title').notNull(),
body: text('body').notNull(),
createdAt: at('created_at').notNull().defaultNow(),
updatedAt: at('updated_at').notNull().defaultNow(),
});
export type Note = typeof notes.$inferSelect;把这些 schema 移动到单独的文件。列表现在接收页大小和偏移量,并设有上限,因此任何请求都不会读取整张表:
import { z } from 'zod';
const title = z.string().trim().min(1).max(200);
const body = z.string().max(10_000);
export const createNoteSchema = z.object({ title, body: body.default('') });
export type CreateNoteDto = z.infer<typeof createNoteSchema>;
// 每个字段都可选,但都不允许 null:title 为 null 时返回 400。
// 不使用 createNoteSchema.partial():默认值会在每次更新时重置 `body`。
export const updateNoteSchema = z.object({ title, body }).partial();
export type UpdateNoteDto = z.infer<typeof updateNoteSchema>;
export const listNotesQuerySchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(20),
offset: z.coerce.number().int().min(0).default(0),
});
export type ListNotesQuery = z.infer<typeof listNotesQuerySchema>;服务查询数据库,数据库由 @InjectDrizzle() 注入:
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { desc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { notes, type Note } from '../database/schema.js';
import type { CreateNoteDto, ListNotesQuery, UpdateNoteDto } from './notes.schemas.js';
@Injectable()
export class NotesService {
constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}
findAll({ limit, offset }: ListNotesQuery): Promise<Note[]> {
return this.db
.select()
.from(notes)
.orderBy(desc(notes.createdAt), desc(notes.id))
.limit(limit)
.offset(offset);
}
async findOne(id: string): Promise<Note> {
const [note] = await this.db.select().from(notes).where(eq(notes.id, id));
return note ?? notFound();
}
async create(dto: CreateNoteDto): Promise<Note> {
const [note] = await this.db.insert(notes).values(dto).returning();
return note;
}
async update(id: string, dto: UpdateNoteDto): Promise<Note> {
// 一条语句完成,写入前不读取:并发 DELETE 删除的记录不会被重新写回。
const [note] = await this.db
.update(notes)
.set({ ...dto, updatedAt: new Date() })
.where(eq(notes.id, id))
.returning();
return note ?? notFound();
}
async remove(id: string): Promise<void> {
const deleted = await this.db.delete(notes).where(eq(notes.id, id)).returning({ id: notes.id });
if (deleted.length === 0) {
notFound();
}
}
}
function notFound(): never {
throw new NotFoundException('Note not found');
}update() 和 remove() 根据语句影响的行数来判断笔记是否存在。如果服务先读取行再保存,两步之间会有一个空档,另一个请求可以删除笔记;随后保存操作会把它重新写回。
import { Body, Controller, Delete, Get, HttpCode, Param, Patch, Post, Query } from '@nestjs/common';
import { z } from 'zod';
import {
createNoteSchema,
listNotesQuerySchema,
updateNoteSchema,
type CreateNoteDto,
type ListNotesQuery,
type UpdateNoteDto,
} from './notes.schemas.js';
import { NotesService } from './notes.service.js';
const noteId = { schema: z.uuid() };
@Controller('notes')
export class NotesController {
constructor(private readonly notesService: NotesService) {}
@Get()
findAll(@Query({ schema: listNotesQuerySchema }) query: ListNotesQuery) {
return this.notesService.findAll(query);
}
@Get(':id')
findOne(@Param('id', noteId) id: string) {
return this.notesService.findOne(id);
}
@Post()
create(@Body({ schema: createNoteSchema }) dto: CreateNoteDto) {
return this.notesService.create(dto);
}
@Patch(':id')
update(@Param('id', noteId) id: string, @Body({ schema: updateNoteSchema }) dto: UpdateNoteDto) {
return this.notesService.update(id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', noteId) id: string) {
return this.notesService.remove(id);
}
}笔记模块注册控制器和服务:
import { Module } from '@nestjs/common';
import { NotesController } from './notes.controller.js';
import { NotesService } from './notes.service.js';
@Module({
controllers: [NotesController],
providers: [NotesService],
})
export class NotesModule {}根模块注册配置、数据库和校验管道。DrizzleModule.forRootAsync() 从 ConfigService 读取 URL,打开一个 pg 连接池,并在应用关闭时关闭它:
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { DrizzleModule } from '@nestjs/drizzle';
import { createObserveModule } from '@nestjs/observe';
import { drizzle } from 'drizzle-orm/node-postgres';
import { envSchema, type Env } from './config.js';
import { NotesModule } from './notes/notes.module.js';
export const { ObserveModule, ObserveInstrument } = createObserveModule();
@Module({
imports: [
// 放在第一位,因此它最后关闭,仍能发送其他模块记录的数据。
ObserveModule.forRoot({
// 在 `npx @nestjs/observe link` 把密钥对写入 .env 之前保持为空;此时 SDK 不发送任何内容。
appKey: process.env.OBSERVE_APP_KEY ?? '',
appSecret: process.env.OBSERVE_APP_SECRET ?? '',
serviceId: 'notes-api',
}),
ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
DrizzleModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
drizzle,
connection: config.get('DATABASE_URL', { infer: true }),
}),
}),
NotesModule,
],
providers: [{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe }],
})
export class AppModule {}ObserveModule放在第一位,与 SDK 快速开始 一致:模块按相反顺序关闭,所以它最后停止,并发送其他模块记录的数据(参见关闭)。createObserveModule()返回它以及ObserveInstrument,main.ts将后者传给 Nest。- 在关联项目之前,密钥对为空。 没有密钥对时,SDK 不发送任何内容,并在启动时说明这一点。
npx @nestjs/observe link会把OBSERVE_APP_KEY和OBSERVE_APP_SECRET写入.env,并把--env-file .env添加到start脚本,使这些变量在AppModule被导入、SDK 读取它们之前就进入环境;ConfigModule加载文件的时间太晚,来不及供 SDK 读取(参见从终端关联)。空值会回退到环境变量,就像nest new写入的占位值一样(参见从环境变量读取密钥对)。
校验管道从 main.ts 移到了 APP_PIPE 提供者。它仍然应用于所有路由,并且现在是 AppModule 的一部分,因此本教程末尾的端到端测试也能获得它,无需重复 main.ts 中的设置。main.ts 从根模块导入 ObserveInstrument,并在应用选项中传入它:
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { AppModule, ObserveInstrument } from './app.module.js';
import type { Env } from './config.js';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
instrument: ObserveInstrument,
});
app.enableShutdownHooks();
const config = app.get<ConfigService<Env, true>>(ConfigService);
await app.listen(config.get('PORT', { infer: true }));enableShutdownHooks() 让应用在收到 SIGTERM 时关闭;容器平台每次部署都会发送这个信号。HTTP 服务器停止接受新连接,连接池被关闭。没有它,进程只会直接结束。
在项目根目录添加 drizzle.config.ts:
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'postgresql',
schema: './src/database/schema.ts',
out: './drizzle',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});根据 schema 生成第一个迁移并应用它(参见迁移):
$ npx drizzle-kit generate --name=notes
$ npx drizzle-kit migrate重启应用。现在笔记在重启后仍然保留,配置错误会在应用处理请求之前阻止启动:
$ DATABASE_URL=not-a-url npm run start
ERROR [ExceptionHandler] Error: Config validation error: DATABASE_URL: Invalid URL使用 JWT 登录用户
目前任何人都可以读取和修改所有笔记。接下来,用户注册、登录获取令牌,并且只能看到自己的笔记。@nestjs/authentication 负责安全敏感的部分:哈希密码、签发和验证令牌,以及轮换刷新令牌。它还注册一个全局守卫,因此除标记为公开的路由外,每个路由都要求已登录用户:
$ npm i --save @nestjs/authentication在 .env 中添加签名密钥,长度至少为 32 字节:
# 生成方式:openssl rand -base64 32
JWT_SECRET=配置 schema 要求必须提供该密钥:
import { z } from 'zod';
export const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
// 用于签发访问令牌:至少 32 字节。
JWT_SECRET: z.string().min(32),
});
export type Env = z.infer<typeof envSchema>;schema 中加入三张表:用户表、供包保存刷新令牌的 refresh_tokens 表,以及每条笔记的所有者:
import { boolean, index, jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
email: text('email').notNull().unique(),
passwordHash: text('password_hash').notNull(),
createdAt: at('created_at').notNull().defaultNow(),
});
export const notes = pgTable(
'notes',
{
id: uuid('id').primaryKey().defaultRandom(),
ownerId: uuid('owner_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
title: text('title').notNull(),
body: text('body').notNull(),
createdAt: at('created_at').notNull().defaultNow(),
updatedAt: at('updated_at').notNull().defaultNow(),
},
(table) => [index('notes_owner_id_created_at_idx').on(table.ownerId, table.createdAt)],
);
// `@nestjs/authentication` 为刷新令牌保存的数据,以其 SHA-256 作为键存储。
export const refreshTokens = pgTable(
'refresh_tokens',
{
id: text('id').primaryKey(),
familyId: text('family_id').notNull(),
userId: text('user_id').notNull(),
createdAt: at('created_at').notNull(),
expiresAt: at('expires_at').notNull(),
familyExpiresAt: at('family_expires_at').notNull(),
usedAt: at('used_at'),
// 族中任意令牌被撤销时,整个族都会被撤销。
revoked: boolean('revoked').notNull().default(false),
claims: jsonb('claims').$type<Record<string, unknown>>(),
},
(table) => [
index('refresh_tokens_family_id_idx').on(table.familyId),
index('refresh_tokens_user_id_idx').on(table.userId),
index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
],
);
export type Note = typeof notes.$inferSelect;生成迁移并应用。owner_id 是必填项,而上一节创建的笔记没有所有者,因此先清空该表(仅在开发环境):
$ docker exec notes-db psql -U postgres -d notes -c "TRUNCATE notes"
$ npx drizzle-kit generate --name=users
$ npx drizzle-kit migrate用户
这个包从不读取你的用户表。它向你的代码请求用户,由你的代码决定什么是用户:
export interface User {
id: string;
email: string;
createdAt: Date;
}仓储是唯一能看到密码哈希的代码。它返回的所有内容都是不含哈希的 User,因此用户对象可以从路由返回或写入日志,而不会泄露哈希:
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { users } from '../database/schema.js';
import type { User } from './user.js';
const columns = { id: users.id, email: users.email, createdAt: users.createdAt };
/** 离开这个类的只能是 `User` 对象:密码哈希保留在内部。 */
@Injectable()
export class UsersRepository {
constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}
/** 新用户;邮箱已被占用时返回 `null`。 */
async create(email: string, passwordHash: string): Promise<User | null> {
// 一条语句:两个使用相同邮箱的注册请求不会都成功。
const [user] = await this.db
.insert(users)
.values({ email: normalize(email), passwordHash })
.onConflictDoNothing({ target: users.email })
.returning(columns);
return user ?? null;
}
async findById(id: string): Promise<User | null> {
const [user] = await this.db.select(columns).from(users).where(eq(users.id, id));
return user ?? null;
}
/** 仅用于密码登录。 */
async findCredentials(email: string): Promise<{ user: User; passwordHash: string } | null> {
const [row] = await this.db.select().from(users).where(eq(users.email, normalize(email)));
if (!row) {
return null;
}
const { passwordHash, ...user } = row;
return { user, passwordHash };
}
async updatePasswordHash(id: string, passwordHash: string): Promise<void> {
await this.db.update(users).set({ passwordHash }).where(eq(users.id, id));
}
}
const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();GET /me 返回已登录用户。@CurrentUser() 注入认证守卫为当前请求加载的用户:
import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import type { User } from './user.js';
@Controller('me')
export class MeController {
@Get()
me(@CurrentUser() user: User) {
return user;
}
}用户模块注册控制器和仓储,并导出仓储供认证代码使用:
import { Module } from '@nestjs/common';
import { MeController } from './me.controller.js';
import { UsersRepository } from './users.repository.js';
@Module({
controllers: [MeController],
providers: [UsersRepository],
exports: [UsersRepository],
})
export class UsersModule {}只需告诉包一次你的用户类型,之后 @CurrentUser('id') 就只接受 User 的键:
import type { User } from '../users/user.js';
declare module '@nestjs/authentication' {
interface AuthenticationTypes {
user: User;
}
}密码与令牌
PasswordHasher 使用 node:crypto 中的 scrypt,在 libuv 线程池中按照 OWASP 推荐的参数哈希密码。一个服务封装控制器需要的两项功能:
import { ConflictException, Injectable } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';
@Injectable()
export class CredentialsService {
constructor(
private readonly usersRepository: UsersRepository,
private readonly passwordHasher: PasswordHasher,
) {}
async register(email: string, password: string): Promise<User> {
const user = await this.usersRepository.create(email, await this.passwordHasher.hash(password));
if (!user) {
throw new ConflictException('Email already registered');
}
return user;
}
/** 用户;邮箱或密码错误时返回 `null`。 */
async verify(email: string, password: string): Promise<User | null> {
const found = await this.usersRepository.findCredentials(email);
// 没有账号时,verify() 会校验一个虚拟哈希,因此响应
// 时间不会泄露哪些邮箱已注册。
const valid = await this.passwordHasher.verify(password, found?.passwordHash);
if (!valid || !found) {
return null;
}
if (this.passwordHasher.needsRehash(found.passwordHash)) {
await this.usersRepository.updatePasswordHash(found.user.id, await this.passwordHasher.hash(password));
}
return found.user;
}
}verify() 总是调用 passwordHasher.verify(),即使用户不存在。如果遇到未知邮箱就提前返回,响应只需几毫秒,而密码错误需要几百毫秒,任何人都能从响应时间判断哪些邮箱已注册。
凭据提供者(credential provider)把请求转换为用户。JwtBearerProvider 读取 Authorization 头,检查令牌的签名、exp、iss 和 aud,并把验证后的声明传给 validate(),由它加载用户:
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';
@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
constructor(
private readonly usersRepository: UsersRepository,
registry: AuthenticationRegistry,
) {
// 密钥、签发者和受众来自 `accessToken` 选项。
super({ realm: 'notes' });
registry.registerProvider(this);
}
// 签名、`exp`、`iss` 和 `aud` 校验通过后调用。
// 返回 null(用户已被删除)会拒绝该令牌。
validate({ sub }: JwtClaims) {
return sub ? this.usersRepository.findById(sub) : null;
}
}登录路由的请求体:
import { z } from 'zod';
export const signUpSchema = z.object({
email: z.email(),
password: z.string().min(12).max(128),
});
export type SignUpDto = z.infer<typeof signUpSchema>;
// 这里不设最小长度:在旧规则下设置的密码仍然可以登录。
export const signInSchema = z.object({
email: z.email(),
password: z.string().max(128),
});
export type SignInDto = z.infer<typeof signInSchema>;
export const refreshTokenSchema = z.object({
refreshToken: z.string().min(1),
});
export type RefreshTokenDto = z.infer<typeof refreshTokenSchema>;控制器使用 TokenService 签发令牌:
import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import {
refreshTokenSchema,
signInSchema,
signUpSchema,
type RefreshTokenDto,
type SignInDto,
type SignUpDto,
} from './auth.schemas.js';
import { CredentialsService } from './credentials.service.js';
@Public()
@Controller('auth')
export class AuthController {
constructor(
private readonly credentialsService: CredentialsService,
private readonly tokenService: TokenService,
) {}
@Post('sign-up')
async signUp(@Body({ schema: signUpSchema }) body: SignUpDto) {
const user = await this.credentialsService.register(body.email, body.password);
return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
}
@Post('token')
@HttpCode(200)
async token(@Body({ schema: signInSchema }) body: SignInDto) {
const user = await this.credentialsService.verify(body.email, body.password);
if (!user) {
throw new UnauthorizedException('Invalid email or password');
}
return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
}
// 未知、已过期或已重复使用的刷新令牌会得到 401。
@Post('token/refresh')
@HttpCode(200)
refresh(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
return this.tokenService.refresh(body.refreshToken);
}
// 登出当前设备。未知令牌返回相同结果,与 RFC 7009 一致。
@Post('token/revoke')
@HttpCode(204)
async revoke(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
await this.tokenService.revoke(body.refreshToken);
}
}- 类上的
@Public()跳过这四个路由的认证。应用的其他所有路由都要求有效的访问令牌。 POST路由默认返回201 Created。为已有账号签发令牌不会创建任何资源,因此token和refresh设置@HttpCode(200)。issue()返回一个访问令牌(使用下一步的accessToken选项签名)、一个刷新令牌,以及以秒为单位的访问令牌有效期expiresIn。refresh()消耗一个刷新令牌,并返回它的后继令牌以及一个新的访问令牌。如果一个已消耗的刷新令牌再次出现,说明有两方持有它:窃贼和客户端,因此包会撤销整个令牌族,双方都必须重新登录。参见向移动应用签发令牌。
存储刷新令牌
刷新令牌是状态,包通过你注册的存储来保存状态。没有存储时,它把令牌保存在内存中,重启后会丢失,也无法在实例间共享;当 NODE_ENV 为 production 时,包会拒绝以这种方式启动。下面的存储使用 Drizzle 实现 RefreshTokenStore,并在构造函数中注册自己:
import { Injectable } from '@nestjs/common';
import { AuthenticationStorage, type RefreshTokenRecord, type RefreshTokenStore } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq, inArray, isNull, lte, type SQL } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { refreshTokens } from '../database/schema.js';
/** 保存在 PostgreSQL 中的刷新令牌,由 API 的所有实例共享。 */
@Injectable()
export class DrizzleRefreshTokenStore implements RefreshTokenStore {
constructor(
@InjectDrizzle() private readonly db: NodePgDatabase,
storage: AuthenticationStorage,
) {
storage.registerSource({ refreshTokens: this });
}
async getRefreshToken(id: string): Promise<RefreshTokenRecord | undefined> {
const [row] = await this.db.select().from(refreshTokens).where(eq(refreshTokens.id, id));
if (!row) {
return undefined;
}
const { revoked: _, usedAt, claims, ...token } = row;
return { ...token, usedAt: usedAt ?? undefined, claims: claims ?? undefined };
}
async saveRefreshToken(record: RefreshTokenRecord): Promise<void> {
await this.db.insert(refreshTokens).values(record);
// 超过绝对有效期的令牌族可以删除。
// 与撤销操作一样,按 id 顺序锁定;否则撤销一个已过期令牌族时,
// 删除它的操作可能与该操作发生死锁。
const expired = this.db
.select({ id: refreshTokens.id })
.from(refreshTokens)
.where(lte(refreshTokens.familyExpiresAt, record.createdAt))
.orderBy(refreshTokens.id)
.for('update');
await this.db.delete(refreshTokens).where(inArray(refreshTokens.id, expired));
}
async markRefreshTokenUsed(id: string, at: Date): Promise<boolean> {
// 条件更新:使用同一令牌的两个刷新请求中,只有一个能更新行。
const updated = await this.db
.update(refreshTokens)
.set({ usedAt: at })
.where(and(eq(refreshTokens.id, id), isNull(refreshTokens.usedAt)))
.returning({ id: refreshTokens.id });
return updated.length === 1;
}
async revokeRefreshTokenFamily(familyId: string): Promise<void> {
await this.revokeRefreshTokens(eq(refreshTokens.familyId, familyId));
}
async isRefreshTokenFamilyRevoked(familyId: string): Promise<boolean> {
const revoked = await this.db
.select({ id: refreshTokens.id })
.from(refreshTokens)
.where(and(eq(refreshTokens.familyId, familyId), eq(refreshTokens.revoked, true)))
.limit(1);
return revoked.length > 0;
}
async revokeUserRefreshTokens(userId: string): Promise<void> {
await this.revokeRefreshTokens(eq(refreshTokens.userId, userId));
}
/**
* 更新前按 id 顺序锁定行。对被重复使用的令牌进行并发刷新时,每个请求都会
* 撤销令牌族;如果两条多行 UPDATE 以不同顺序锁定相同的行,就会死锁:
* 失败方会返回 500,而不是 401。
*/
private async revokeRefreshTokens(rows: SQL): Promise<void> {
const locked = this.db.select({ id: refreshTokens.id }).from(refreshTokens).where(rows).orderBy(refreshTokens.id).for('update');
await this.db.update(refreshTokens).set({ revoked: true }).where(inArray(refreshTokens.id, locked));
}
}markRefreshTokenUsed() 是最关键的方法。它是一条条件 UPDATE,因此当窃贼和客户端同时使用同一令牌刷新时,恰好只有一方成功,另一方的尝试会撤销整个令牌族。如果存储先读取行、检查 usedAt 再写回,两方都会通过。存储契约 列出了每个方法的规则,本教程末尾的测试 会检查这些规则。
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { AuthController } from './auth.controller.js';
import { CredentialsService } from './credentials.service.js';
import { DrizzleRefreshTokenStore } from './drizzle-refresh-token.store.js';
import { JwtAuth } from './jwt-auth.provider.js';
@Module({
imports: [UsersModule],
controllers: [AuthController],
providers: [JwtAuth, CredentialsService, DrizzleRefreshTokenStore],
})
export class AuthModule {}注册模块
在根模块中注册 AuthenticationModule,配置访问令牌的密钥、签发者、受众和有效期,以及刷新令牌的有效期:
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthModule } from './auth/auth.module.js';
import { UsersModule } from './users/users.module.js';
// ...
@Module({
imports: [
ObserveModule.forRoot({
// ...
}),
ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
DrizzleModule.forRootAsync({
// ...
}),
AuthenticationModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({
accessToken: {
key: config.get('JWT_SECRET', { infer: true }),
issuer: 'notes-api',
audience: 'notes-api',
ttl: '15m',
},
refreshToken: { ttl: '30d', absoluteTtl: '90d' },
}),
}),
UsersModule,
AuthModule,
NotesModule,
],
providers: [{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe }],
})
export class AppModule {}使用密钥作为密钥时,令牌使用 HS256 签名。访问令牌有效期为 15 分钟,刷新令牌为 30 天,无论轮换多频繁,一个刷新令牌族最长存在 90 天。有效期可以使用毫秒数或 '15m' 这样的字符串;与 @nestjs/jwt 不同,纯数字不代表秒。
笔记归其所有者所有
现在每个笔记查询都包含所有者。服务把用户 ID 作为第一个参数:
import { and, desc, eq } from 'drizzle-orm';
// ...
@Injectable()
export class NotesService {
constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}
findAll(ownerId: string, { limit, offset }: ListNotesQuery): Promise<Note[]> {
return this.db
.select()
.from(notes)
.where(eq(notes.ownerId, ownerId))
.orderBy(desc(notes.createdAt), desc(notes.id))
.limit(limit)
.offset(offset);
}
async findOne(ownerId: string, id: string): Promise<Note> {
const [note] = await this.db.select().from(notes).where(this.owned(ownerId, id));
return note ?? notFound();
}
async create(ownerId: string, dto: CreateNoteDto): Promise<Note> {
const [note] = await this.db
.insert(notes)
.values({ ...dto, ownerId })
.returning();
return note;
}
async update(ownerId: string, id: string, dto: UpdateNoteDto): Promise<Note> {
// 一条条件语句:没有先读后写的空档,而且他人的笔记与不存在的笔记
// 同样被视为不存在。
const [note] = await this.db
.update(notes)
.set({ ...dto, updatedAt: new Date() })
.where(this.owned(ownerId, id))
.returning();
return note ?? notFound();
}
async remove(ownerId: string, id: string): Promise<void> {
const deleted = await this.db.delete(notes).where(this.owned(ownerId, id)).returning({ id: notes.id });
if (deleted.length === 0) {
notFound();
}
}
private owned(ownerId: string, id: string) {
return and(eq(notes.id, id), eq(notes.ownerId, ownerId));
}
}所有者是每条语句 WHERE 子句的一部分,而不是在读取后检查,因此没有遗漏的余地,也不存在检查与写入之间的空档。他人的笔记返回 404,与不存在的笔记返回的结果相同,不会告诉任何人哪些 ID 正在使用。
控制器通过 @CurrentUser('id') 传入已登录用户的 ID:
import { CurrentUser } from '@nestjs/authentication';
// ...
@Controller('notes')
export class NotesController {
constructor(private readonly notesService: NotesService) {}
@Get()
findAll(@CurrentUser('id') userId: string, @Query({ schema: listNotesQuerySchema }) query: ListNotesQuery) {
return this.notesService.findAll(userId, query);
}
@Get(':id')
findOne(@CurrentUser('id') userId: string, @Param('id', noteId) id: string) {
return this.notesService.findOne(userId, id);
}
@Post()
create(@CurrentUser('id') userId: string, @Body({ schema: createNoteSchema }) dto: CreateNoteDto) {
return this.notesService.create(userId, dto);
}
@Patch(':id')
update(
@CurrentUser('id') userId: string,
@Param('id', noteId) id: string,
@Body({ schema: updateNoteSchema }) dto: UpdateNoteDto,
) {
return this.notesService.update(userId, id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@CurrentUser('id') userId: string, @Param('id', noteId) id: string) {
return this.notesService.remove(userId, id);
}
}重启应用。启动时,模块会记录提供者链以及刷新令牌的存储位置:
LOG [AuthenticationModule] AuthenticationRegistry: providers JwtAuth
LOG [AuthenticationModule] AuthenticationStorage: DrizzleRefreshTokenStore (refreshTokens)没有令牌的请求会得到 401,并说明 API 接受什么认证方式:
$ curl -i localhost:3000/notes
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="notes"
{"message":"Unauthorized","statusCode":401,"errorCode":"missing_credentials"}注册用户。响应中带有令牌(这里和下文都做了缩短):
$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"6fUCXRhy1e5O-3wb...","expiresIn":900}使用访问令牌访问笔记:
$ TOKEN=eyJhbGciOiJIUzI1NiIs...
$ curl localhost:3000/notes -H "Authorization: Bearer $TOKEN" --json '{"title":"Ship the guide"}'
{"id":"30694f2b-551c-40ab-b0ed-f789acd6381b","ownerId":"43bec047-ad99-4c34-b3e7-3f415127213d","title":"Ship the guide","body":"","createdAt":"2026-11-19T19:57:21.213Z","updatedAt":"2026-11-19T19:57:21.213Z"}
$ curl localhost:3000/me -H "Authorization: Bearer $TOKEN"
{"id":"43bec047-ad99-4c34-b3e7-3f415127213d","email":"ada@example.com","createdAt":"2026-11-19T19:57:21.095Z"}第二个注册的用户获取 Ada 的笔记时会得到 404,列表也是空的。访问令牌过期后,客户端用刷新令牌换取新令牌。同一个刷新令牌使用两次会撤销其令牌族,因此连后继令牌也会失效:
$ curl localhost:3000/auth/token/refresh --json '{"refreshToken":"6fUCXRhy1e5O-3wb..."}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"6CnPc_hiBJUwDubp...","expiresIn":900}
$ curl localhost:3000/auth/token/refresh --json '{"refreshToken":"6fUCXRhy1e5O-3wb..."}'
{"message":"Refresh token reused","error":"Unauthorized","statusCode":401}
$ curl localhost:3000/auth/token/refresh --json '{"refreshToken":"6CnPc_hiBJUwDubp..."}'
{"message":"Refresh token invalid","error":"Unauthorized","statusCode":401}被篡改或已过期的访问令牌会得到 401,并按照 RFC 6750 的规定告诉客户端原因:
WWW-Authenticate: Bearer realm="notes", error="invalid_token", error_description="invalid signature"对登录限流
目前没有任何东西阻止脚本以服务器响应速度尝试密码。@nestjs/throttler 用于限制请求速率:
$ npm i --save @nestjs/throttler登录仅按 IP 地址限流过于粗糙:同一办公室或运营商地址后的用户会共享额度。像认证章节 一样,使用两个限流器定义。default 在所有路由上按 IP 地址计数;account 在请求体指明账号时,按邮箱和 IP 地址计数:
/** 请求体指明的地址,去除首尾空白、转为小写并规范化为 Unicode NFC;没有则返回 `''`。 */
export function accountEmail(req: { body?: { email?: unknown } }): string {
const email = req.body?.email;
return typeof email === 'string' ? email.trim().normalize('NFC').toLowerCase() : '';
}在根模块中注册两个定义,并把 ThrottlerGuard 设为全局守卫:
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { accountEmail } from './auth/account-email.js';
// ...
@Module({
imports: [
// ...
ThrottlerModule.forRoot([
// 所有路由上均按 IP 地址计数。
{ name: 'default', ttl: minutes(1), limit: 100 },
// 请求体指明账号时,按邮箱和 IP 地址计数。
{
name: 'account',
ttl: minutes(15),
limit: 5,
skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
},
]),
UsersModule,
AuthModule,
NotesModule,
],
providers: [
{ provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
{ provide: APP_GUARD, useClass: ThrottlerGuard },
],
})
export class AppModule {}限流器守卫注册在根模块中,因此它在认证守卫之前运行,使用猜测令牌的请求也会计入额度。收紧登录路由:
import { SkipThrottle, Throttle, hours, minutes } from '@nestjs/throttler';
// ...
@SkipThrottle({ account: true })
@Throttle({ default: { limit: 10, ttl: hours(1) } })
@Post('sign-up')
// ...
@Throttle({
default: { limit: 30, ttl: minutes(15) },
account: { limit: 5, ttl: minutes(15) },
})
@Post('token')
// ...每次注册都使用一个新地址,因此注册路由跳过 account 额度,改为按 IP 地址限流。同一账号输错五次密码后,第六次尝试会得到 429,而其他账号仍可从同一地址登录:
$ curl -i localhost:3000/auth/token --json '{"email":"dave@example.com","password":"guess 6"}'
HTTP/1.1 429 Too Many Requests
Retry-After-account: 900
{"statusCode":429,"message":"ThrottlerException: Too Many Requests"}限流器默认在内存中计数,因此每个实例各自计数。运行多个实例时,请使用 Redis 等共享存储。位于负载均衡器之后时,向 NodeAdapter 传入 trustProxy 选项(参见Node 适配器选项),让追踪器看到客户端地址而不是代理地址。
设置安全响应头和 CORS
还有两项设置位于任何供浏览器调用的 API 的边缘。安全响应头告诉浏览器启用各种保护,例如拒绝被框架嵌入,或禁止猜测响应的内容类型。CORS 决定哪些网站的脚本可以从访客浏览器调用 API 并读取响应。
Nest 从 v12.1 起内置了 app.useSecurityHeaders(),它会发送 Helmet 默认会发送的响应头,无需安装包(参见安全响应头)。请在创建应用后立即调用它,这样每个响应(包括错误响应)都会带上这些响应头。CORS 的来源从配置读取:
// ...
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
instrument: ObserveInstrument,
});
app.useSecurityHeaders();
app.enableShutdownHooks();
const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });
await app.listen(config.get('PORT', { infer: true }));来源是一个逗号分隔的变量,配置 schema 把它转换为 URL 列表;如果其中任何一个不是 URL,就在启动时拒绝启动:
import { z } from 'zod';
export const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.url(),
// 用于签发访问令牌:至少 32 字节。
JWT_SECRET: z.string().min(32),
// 允许调用 API 的浏览器来源,逗号分隔。默认不允许任何来源。
CORS_ORIGINS: z
.string()
.default('')
.transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
.pipe(z.array(z.url())),
});
export type Env = z.infer<typeof envSchema>;在 .env 中列出 Web 应用的来源:
CORS_ORIGINS=https://app.example.com- 默认不允许任何来源。 不带
origin调用enableCors()时,它会用Access-Control-Allow-Origin: *响应所有网站,因此已登录用户访问的任何页面都可以从浏览器调用 API 并读取响应(参见默认允许的来源)。使用空列表时,任何网站都不能调用;curl、移动应用和其他服务器不受影响,因为 CORS 由浏览器强制执行。 - 不设置
credentials选项。 API 使用 Bearer 令牌认证,Web 应用自己在Authorization头中发送它。这里不涉及 Cookie,也不涉及与之配套的credentials: true。 - Swagger UI 仍然可用。 它从应用自身加载脚本和样式表,默认的
Content-Security-Policy允许这些资源。但是,如果通过除localhost以外的地址以纯 HTTP 提供页面,其资源会被升级为 HTTPS 并加载失败;参见Swagger UI 与 GraphQL IDE。
现在每个响应都带有这些响应头(这里省略了一部分):
$ curl -i localhost:3000/health/live
HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
...浏览器在发起带 Authorization 头的跨域 PATCH 请求之前会先询问。列出的来源会得到响应:
$ curl -i -X OPTIONS localhost:3000/notes -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: PATCH" -H "Access-Control-Request-Headers: authorization,content-type"
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: authorization,content-type任何其他来源都不会得到 Access-Control-Allow-Origin 响应头,因此其浏览器会拒绝发送请求:
$ curl -i -X OPTIONS localhost:3000/notes -H "Origin: https://evil.example" -H "Access-Control-Request-Method: PATCH" -H "Access-Control-Request-Headers: authorization"
HTTP/1.1 204 No Content
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: authorization使用 OpenAPI 描述 API
@nestjs/swagger 根据控制器生成 OpenAPI 文档。Zod 4.2 及更高版本本身提供 JSON Schema,因此请求体和查询参数来自与校验它们相同的 schema,无需额外配置(参见Standard Schema):
$ npm i --save @nestjs/swagger在 main.ts 中构建文档并提供 Swagger UI。addSecurityRequirements('bearer') 声明每个操作都需要 Bearer 令牌,这正是 API 的行为:认证守卫是全局的,只有标记为 @Public() 的路由会跳过它:
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
// ...
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
instrument: ObserveInstrument,
});
app.useSecurityHeaders();
// ...
const document = new DocumentBuilder()
.setTitle('Notes API')
.setVersion('1.0')
.addBearerAuth()
.addSecurityRequirements('bearer')
.build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));Swagger 不知道 @Public(),因此也要为它标记公开路由。@ApiSecurity() 传入空要求,表示某个操作无需认证,Swagger UI 也不会在它旁边显示锁图标:
import { ApiSecurity } from '@nestjs/swagger';
// ...
@Public()
@ApiSecurity({})
@Controller('auth')
export class AuthController {
// ...
}Swagger UI 位于 http://localhost:3000/docs,文档位于 http://localhost:3000/docs-json。在 Authorize 下输入令牌后,Swagger UI 会在每个需要令牌的请求中发送它。其中的 POST /notes 请求体是转换后的 Zod schema:
{
"type": "object",
"properties": {
"title": { "type": "string", "minLength": 1, "maxLength": 200 },
"body": { "default": "", "type": "string", "maxLength": 10000 }
},
"required": ["title"]
}添加健康检查
容器平台会问两个问题:进程是否还活着,以及它现在能否处理请求。@nestjs/terminus 可以回答这两个问题:
$ npm i --save @nestjs/terminusTerminus 没有针对 Drizzle 的指示器,因此就绪检查通过自定义指示器 执行查询:
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { HealthIndicatorService } from '@nestjs/terminus';
import { sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
@Injectable()
export class DatabaseHealthIndicator {
constructor(
private readonly healthIndicatorService: HealthIndicatorService,
@InjectDrizzle() private readonly db: NodePgDatabase,
) {}
isHealthy(key: string) {
return this.healthIndicatorService
.check(key)
.attempt(async () => {
await this.db.execute(sql`select 1`);
})
.withTimeout('1s');
}
}控制器暴露这两个检查,它们都是公开的,并且不受限流影响:
import { Controller, Get } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
import { SkipThrottle } from '@nestjs/throttler';
import { DatabaseHealthIndicator } from './database.health.js';
@Public()
@ApiSecurity({})
@SkipThrottle()
@Controller('health')
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly database: DatabaseHealthIndicator,
) {}
@Get('live')
@HealthCheck()
live() {
return this.health.check([]);
}
@Get('ready')
@HealthCheck()
ready() {
return this.health.check([() => this.database.isHealthy('database')]);
}
}健康模块导入 Terminus 并提供指示器:
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { DatabaseHealthIndicator } from './database.health.js';
import { HealthController } from './health.controller.js';
@Module({
imports: [TerminusModule],
controllers: [HealthController],
providers: [DatabaseHealthIndicator],
})
export class HealthModule {}把 HealthModule 添加到 AppModule 的 imports 中。这些检查是公开的,并且跳过限流,因为平台每隔几秒就会调用它们。存活检查不查看数据库:重启进程无法修复数据库。当数据库停止响应时,就绪检查会在一秒超时内失败,平台会停止向该实例发送流量,直到检查再次通过:
$ curl localhost:3000/health/ready
{"status":"ok","info":{"database":{"responseTime":2,"status":"up"}},"error":{},"details":{"database":{"responseTime":2,"status":"up"}}}
$ docker pause notes-db
$ curl -i localhost:3000/health/ready
HTTP/1.1 503 Service Unavailable
{"status":"error","info":{},"error":{"database":{"message":"timeout of 1000ms exceeded","responseTime":1001,"status":"down"}},"details":{"database":{"message":"timeout of 1000ms exceeded","responseTime":1001,"status":"down"}}}
$ docker unpause notes-db以 JSON 格式记录日志
开发环境下,Nest 的日志记录器输出易读的文本行。生产环境下,平台收集进程写入 stdout 的内容;如果每一行都是可以按级别、上下文或任意字段过滤的 JSON 对象,日志搜索会更有用。Nest 的 ConsoleLogger 自己就能输出 JSON(参见JSON 日志):
import { ConsoleLogger } from '@nestjs/common';
// ...
const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
instrument: ObserveInstrument,
logger: new ConsoleLogger({
// 生产环境每行一个 JSON 对象;开发环境输出易读文本。
json: production,
// 无论这些属性出现在已记录对象的什么位置,都对其进行掩码。
redact: ['password', 'authorization', 'accessToken', 'refreshToken'],
}),
});
app.useSecurityHeaders();
// ...- 日志记录器在
ConfigModule读取.env之前创建,因此它从进程环境读取NODE_ENV,而生产环境通常由平台在那里设置它。 redact是安全网。 在已记录对象的任意深度、任意大小写下,只要出现这些名称之一的属性,其值就会写成"[REDACTED]"。哪天有人调试时记录了整个请求体或请求头,密码和令牌也不会进入日志。它只处理对象,不处理字符串:消息本身会原样输出,因此不要把秘密插值到消息中(参见脱敏敏感值)。
一条值得记录的日志:登录失败时,把地址作为结构化参数,而不是放进消息:
import { Body, Controller, HttpCode, Logger, Post, UnauthorizedException } from '@nestjs/common';
// ...
export class AuthController {
private readonly logger = new Logger(AuthController.name);
// ...
async token(@Body({ schema: signInSchema }) body: SignInDto) {
const user = await this.credentialsService.verify(body.email, body.password);
if (!user) {
this.logger.warn('Sign-in failed', { email: body.email });
throw new UnauthorizedException('Invalid email or password');
}
// ...
}
}开发环境中密码错误时:
WARN [AuthController] Sign-in failed { email: 'ada@example.com' }生产环境中(NODE_ENV=production)的同一条日志:
{"level":"warn","pid":19998,"timestamp":1795163181664,"message":"Sign-in failed","context":"AuthController","params":{"email":"ada@example.com"}}现在日志搜索可以按地址统计登录失败次数,你就能发现有人不顾限流仍在猜测某个账号。安装 NestJS Observe 后,请求期间写入的每一行日志还会带上该请求的追踪 ID(参见生产环境日志)。
测试
端到端测试会在两项改动后启动真实的 AppModule。数据库使用 PGlite,即编译为 WebAssembly 的 PostgreSQL,并应用真实迁移,因此测试不需要服务器。PasswordHasher 使用成本更低的 scrypt 参数,因为默认参数每次哈希需要几百毫秒和 128 MiB 内存,这是有意设计的。测试使用标准 Nest 项目的 Vitest 配置,并通过 Node 适配器提供的 app.inject() 发送请求,因此也不需要监听服务器:
$ npm i --save-dev @nestjs/testing vitest vite @electric-sql/pglite测试配置为应用提供启动校验所需的环境变量:
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
root: './',
include: ['test/**/*.e2e-spec.ts'],
env: {
DATABASE_URL: 'postgres://unused-in-tests',
JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
},
},
});测试覆盖无令牌请求、仅所有者可见的笔记,以及刷新令牌轮换:
import { fileURLToPath } from 'node:url';
import { PGlite } from '@electric-sql/pglite';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { drizzle } from 'drizzle-orm/pglite';
import { migrate } from 'drizzle-orm/pglite/migrator';
import { AppModule } from '../src/app.module.js';
describe('Notes API (e2e)', () => {
const pglite = new PGlite(); // PostgreSQL in-process: no server to start
let app: NestNodeApplication;
beforeAll(async () => {
const db = drizzle({ client: pglite });
await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
.overrideProvider(getDrizzleToken())
.useValue(db)
// 默认成本的 scrypt 每次哈希需要 128 MiB 和几百毫秒。
.overrideProvider(PasswordHasher)
.useValue(new PasswordHasher({ logN: 10 }))
.compile();
app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
await app.init();
});
afterAll(async () => {
await app.close();
await pglite.close();
});
async function signUp(email: string) {
const res = await app.inject({
method: 'POST',
url: '/auth/sign-up',
payload: { email, password: 'correct horse battery' },
});
expect(res.statusCode).toBe(201);
return res.json<{ accessToken: string; refreshToken: string }>();
}
it('rejects requests without a token', async () => {
const res = await app.inject({ method: 'GET', url: '/notes' });
expect(res.statusCode).toBe(401);
});
it('creates, updates and lists notes for their owner only', async () => {
const ada = await signUp('ada@example.com');
const bob = await signUp('bob@example.com');
const asAda = { authorization: `Bearer ${ada.accessToken}` };
const asBob = { authorization: `Bearer ${bob.accessToken}` };
const created = await app.inject({
method: 'POST',
url: '/notes',
headers: asAda,
payload: { title: 'Buy milk', body: '2 litres' },
});
expect(created.statusCode).toBe(201);
const { id } = created.json<{ id: string }>();
const nulled = await app.inject({ method: 'PATCH', url: `/notes/${id}`, headers: asAda, payload: { title: null } });
expect(nulled.statusCode).toBe(400);
const renamed = await app.inject({ method: 'PATCH', url: `/notes/${id}`, headers: asAda, payload: { title: 'Buy oat milk' } });
expect(renamed.json()).toMatchObject({ title: 'Buy oat milk', body: '2 litres' });
const stolen = await app.inject({ method: 'GET', url: `/notes/${id}`, headers: asBob });
expect(stolen.statusCode).toBe(404);
const bobsList = await app.inject({ method: 'GET', url: '/notes', headers: asBob });
expect(bobsList.json()).toEqual([]);
});
it('rotates refresh tokens and revokes the family on reuse', async () => {
const { refreshToken } = await signUp('carol@example.com');
const refresh = (token: string) =>
app.inject({ method: 'POST', url: '/auth/token/refresh', payload: { refreshToken: token } });
const first = await refresh(refreshToken);
expect(first.statusCode).toBe(200);
const successor = first.json<{ refreshToken: string }>().refreshToken;
expect((await refresh(refreshToken)).statusCode).toBe(401); // reused: the family is revoked
expect((await refresh(successor)).statusCode).toBe(401);
});
});PGlite 只有单个连接,因此两个请求在那里不会真正并发。刷新令牌存储的保证与并发竞争有关,因此要在真实 PostgreSQL 服务器上、使用连接池,针对 @nestjs/authentication/testing 提供的用例测试存储本身。concurrent: true 会加入对同一令牌的并行刷新,先读后写的存储无法通过这种测试:
import { fileURLToPath } from 'node:url';
import { AuthenticationStorage } from '@nestjs/authentication';
import { authenticationStoreContract } from '@nestjs/authentication/testing';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { DrizzleRefreshTokenStore } from '../src/auth/drizzle-refresh-token.store.js';
// 真实 PostgreSQL 和连接池,并行调用会真正发生竞争。
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)('DrizzleRefreshTokenStore', () => {
const pool = new Pool({ connectionString: url });
const db = drizzle({ client: pool });
beforeAll(async () => {
await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
});
afterAll(() => pool.end());
/** 空表上的存储,不注册到任何地方:测试套件会构建自己的注册表。 */
async function emptyStore() {
await pool.query('TRUNCATE refresh_tokens');
return { refreshTokens: new DrizzleRefreshTokenStore(db, new AuthenticationStorage()) };
}
for (const c of authenticationStoreContract(emptyStore, { contracts: ['refreshTokens'], concurrent: true })) {
it(c.name, c.run);
}
});在 package.json 中添加脚本,并让两个测试针对各自的数据库运行(存储测试会清空它的表):
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"先创建一次测试数据库,然后运行两个文件:
$ docker exec notes-db psql -U postgres -c "CREATE DATABASE notes_test"
$ TEST_DATABASE_URL=postgres://postgres:notes@localhost:5432/notes_test npm run test:e2e
Test Files 2 passed (2)
Tests 8 passed (8)生产环境检查清单
- 把
NODE_ENV设为production。 这样,当认证模块使用的某个功能没有存储时,它会拒绝启动,而不是把令牌保存在单个进程的内存中。 - 把
JWT_SECRET保存在平台的秘密存储中,在运行时注入,不要放进镜像或提交到仓库的.env文件。任何拿到它的人都能为任意用户签发令牌。 - 把
drizzle-kit migrate作为发布步骤运行,在新版本启动之前执行,而不是让每个实例在启动时运行。 - 把
CORS_ORIGINS设为 Web 应用的来源,包含协议(https://),不包含路径。如果没有浏览器调用 API,就留空。 - 使用平台的日志驱动收集 stdout 中的 JSON 日志,不要让进程自己写文件。
- 运行多个实例后,为限流器使用共享存储,并在负载均衡器之后向
NodeAdapter传入trustProxy。 - 根据 scrypt 的需求规划服务器资源。 默认成本下,每次哈希在 libuv 线程池中使用 128 MiB 内存(除非设置
UV_THREADPOOL_SIZE,否则只有四个线程)。登录突发请求会排队,限流器为队列设置上限。 - 让平台探针指向健康检查:存活检查使用
/health/live,就绪检查使用/health/ready。关闭钩子已启用,因此部署时的SIGTERM会在进程退出前关闭服务器和连接池。 - 为生产环境使用独立的 Observe 密钥对,从项目的 API Keys 页面获取,作为
OBSERVE_APP_KEY和OBSERVE_APP_SECRET放入平台环境:start:prod不会加载.env。这样 NestJS Observe 会按路由记录请求及其延迟和失败率、记录每个请求的追踪及其 SQL 查询,并把未处理错误归组为缺陷,出现新缺陷时发送邮件(参见错误监控)。关闭钩子已启用,因此 SDK 会在部署的SIGTERM时发送最后一批数据。 - 明确密码重置或设备被盗会终止什么。
TokenService.revokeAll()会撤销用户的全部刷新令牌,而已经签发的访问令牌会在 15 分钟内过期。
当 API 增加 Web 应用会话、邮箱验证或双因素认证时,认证章节的检查清单 还涵盖其余事项。
接下来
这个 API 已经具备大多数生产 API 所需的部分,每个部分都可以从对应章节继续扩展: