# 授权

来源：https://docs.nestjs.com/security/authorization

`@nestjs/authorization` 把权限表达为**策略**（policy）：策略是类，其方法回答「该用户能否做这件事？」。策略是普通的提供者，因此可以注入服务；每次检查都会针对它所调用的策略方法做类型检查。策略适用于任何数据形态，包括 Prisma、Drizzle 和 Kysely 返回的普通对象。

> info **提示** 若想在完整应用中查看策略，请参考[在 Node.js 中构建电商后端](/tutorials/ecommerce-backend)（只有员工可以编辑商品目录），或[在 Node.js 中构建项目管理 API](/tutorials/project-management-api)（权限逐条记录检查）。

本教程将为一个猫粮与宠物用品网店的 API 加上权限控制：

- 访客与顾客只能浏览已发布的商品。员工还能看到草稿，且只有员工可以编辑商品目录。
- 顾客只能看到自己的订单；员工可以看到全部订单。
- 只有员工可以给订单退款，且只能退已付款的订单，金额不超过财务为每个人单独设定的上限。已发货的订单任何人都不能退款。
- 管理员可以不受限制地管理商品目录。

在此过程中，你会看到每一类检查该放在哪里（路由上还是服务里）、拒绝请求时什么情况下是 401、什么情况下是 403，以及如何测试策略。

#### 前置条件

本教程承接[身份验证](/security/authentication)教程：网店用 `@nestjs/authentication` 让用户登录，而本章决定他们登录后能做什么。先安装该包：

```bash
$ npm i --save @nestjs/authorization
```

如果你从零开始，下面这些文件就是本章依赖的登录代码：即身份验证教程中的应用在[为移动应用签发令牌](/security/authentication#issue-tokens-to-the-mobile-app)之后的状态，精简为移动应用的登录方式——用密码换取持有者令牌。用户仍是同一个普通对象，与你 ORM 返回的形态一致：

```typescript

export type Role = 'customer' | 'staff' | 'admin';

export interface User {
  id: string;
  email: string;
  /** 用户是否已向我们证明该邮箱归其所有，例如通过魔法链接验证。 */
  emailVerified: boolean;
  roles: Role[];
}
```

四个演示账号代替用户表：两位顾客（Alice 和 Bob）、一位员工（Sam），以及既是员工又是管理员的 Ada。它们的 id 是固定的，以便演示订单和测试引用：

```typescript

import type { User } from './user.js';

/**
 * 演示账号。它们都用密码 "catnip4all" 登录，
 * 预置的订单以它们的 id 作为引用。
 */
export const alice: User = {
  id: '1f794c55-472e-42b9-8913-4114964ed6fb',
  email: 'alice@example.com',
  emailVerified: true,
  roles: ['customer'],
};

export const bob: User = {
  id: 'fc27b5c1-62b5-494e-9924-28a66d387fd1',
  email: 'bob@example.com',
  emailVerified: true,
  roles: ['customer'],
};

export const sam: User = {
  id: '208a223b-3503-4255-83e7-22d290e331c3',
  email: 'sam@example.com',
  emailVerified: true,
  roles: ['staff'],
};

export const ada: User = {
  id: 'ae34ca97-f82b-49ab-b332-8808f3b0e240',
  email: 'ada@example.com',
  emailVerified: true,
  roles: ['staff', 'admin'],
};

export const demoUsers = [alice, bob, sam, ada];
```

`UsersRepository` 沿用身份验证教程的实现，只保留本章需要的两个方法。它在启动时写入演示账号，且只有 `User` 对象会离开这个类：密码哈希始终留在内部。

```typescript

import { Injectable, type OnModuleInit } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import { demoUsers } from './demo-users.js';
import type { User } from './user.js';

interface UserRow extends User {
  passwordHash: string | null;
}

/**
 * 内存版的数据层替身（对应 Prisma、Drizzle、TypeORM 等）。
 * 只有 `User` 对象会离开这个类：密码哈希留在内部。
 */
@Injectable()
export class UsersRepository implements OnModuleInit {
  private readonly rows = new Map<string, UserRow>();

  constructor(private readonly passwordHasher: PasswordHasher) {}

  async onModuleInit() {
    // 写入演示账号，密码统一为 "catnip4all"。
    const passwordHash = await this.passwordHasher.hash('catnip4all');
    for (const user of demoUsers) {
      this.rows.set(user.id, { ...user, passwordHash });
    }
  }

  async findById(id: string): Promise<User | null> {
    const row = this.rows.get(id);
    return row ? toUser(row) : null;
  }

  /** 仅供密码登录使用。 */
  async findCredentials(email: string): Promise<{ user: User; passwordHash: string | null } | null> {
    const row = this.findRow(email);
    return row ? { user: toUser(row), passwordHash: row.passwordHash } : null;
  }

  private findRow(email: string) {
    const normalized = normalize(email);
    return [...this.rows.values()].find((row) => row.email === normalized);
  }
}

const normalize = (email: string) => email.trim().toLowerCase();
const toUser = ({ id, email, emailVerified, roles }: UserRow): User => ({ id, email, emailVerified, roles: [...roles] });
```

```typescript

import { Module } from '@nestjs/common';
import { UsersRepository } from './users.repository.js';

@Module({
  providers: [UsersRepository],
  exports: [UsersRepository],
})
export class UsersModule {}
```

令牌沿用身份验证教程签发给移动应用的那一套：短时效的 JWT 访问令牌，由根模块稍后传给 `AuthenticationModule` 的 `accessToken` 选项统一描述。签名密钥即身份验证教程 `.env` 文件中的 `JWT_SECRET`，至少 32 字节：

```bash
# 生成方式：openssl rand -base64 32
JWT_SECRET=
```

> info **提示** 为保持简洁，本教程直接读取 `process.env`。在实际应用中，请通过 [`@nestjs/config`](/application/configuration) 配合校验 schema 加载环境变量，这样缺少密钥时应用会在启动阶段失败，代码中则从 `ConfigService` 读取。

`JwtAuth` 用 `accessToken` 选项校验持有者令牌，并加载令牌对应的用户。它在构造函数中把自己注册到 `AuthenticationRegistry`，守卫正是通过这一注册得知它的存在：

```typescript

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,
  ) {
    // key、issuer 与 audience 都来自 `accessToken` 选项。
    super({ realm: 'store' });
    // 把这个提供者加入守卫为每次请求所跑的校验链。
    registry.registerProvider(this);
  }

  // 在签名与声明校验通过之后调用。
  // 返回 null（用户已被删除）即拒绝该令牌。
  validate({ sub }: JwtClaims) {
    return sub ? this.usersRepository.findById(sub) : null;
  }
}
```

`CredentialsService` 用该包的 `PasswordHasher` 拿密码与已存哈希比对。无论邮箱不存在还是密码错误，它都返回 `null`，且两种情况耗时相同：

```typescript

import { 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,
  ) {}

  /** 校验成功返回用户，邮箱或密码有误时返回 `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?.passwordHash) {
      return null;
    }
    return found.user;
  }
}
```

`TokensController` 用邮箱加密码换取令牌。请求体沿用你应用现有的校验方式。本页每个 DTO 都给两份：一份是带装饰器的类，一份是 Zod schema，挑你用得上的一种，跳过另一段即可：

```typescript

import { IsEmail, IsString } from 'class-validator';

export class SignInDto {
  @IsEmail()
  email: string;

  @IsString()
  password: string;
}
```

```typescript

import { z } from 'zod';

export const signInSchema = z.object({
  email: z.email(),
  password: z.string(),
});
export type SignInDto = z.infer<typeof signInSchema>;
```

`TokenService.issue()` 用同一套 `accessToken` 选项签发访问令牌，并与刷新令牌一并返回：

```typescript

import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import { SignInDto } from './auth.dto.js';
import { CredentialsService } from './credentials.service.js';

@Public()
@Controller('auth/token')
export class TokensController {
  constructor(
    private readonly credentialsService: CredentialsService,
    private readonly tokenService: TokenService,
  ) {}

  @Post()
  @HttpCode(200)
  async issue(@Body() 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',
      // `amr` 会写进这个访问令牌，也会写进之后每一次刷新出的令牌。
      claims: { amr: ['pwd'] },
    });
  }
}
```

改用 Zod schema 时，body 参数声明的是 schema 而非类：

```typescript

import { signInSchema, type SignInDto } from './auth.schemas.js';
// ...
@Post()
@HttpCode(200)
async issue(@Body({ schema: signInSchema }) body: SignInDto) {
  // ...
}
```

> info **提示** DTO 只有在校验管道的作用下才会生效：请全局绑定 `ValidationPipe`——可以注册为 `AppModule` 的 `APP_PIPE` 提供者，也可以在 `main.ts` 中调用 `useGlobalPipes()`。改用 Zod schema 时，则同样地绑定 `StandardSchemaValidationPipe`。一个应用二选一即可。两者的选项见[校验](/application/validation)页面。

```typescript

import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { CredentialsService } from './credentials.service.js';
import { JwtAuth } from './jwt-auth.provider.js';
import { TokensController } from './tokens.controller.js';

@Module({
  imports: [UsersModule],
  controllers: [TokensController],
  providers: [JwtAuth, CredentialsService],
})
export class AuthModule {}
```

身份验证会把已登录的 `User` 挂到 `request.user` 上，`@CurrentUser()` 则可把它注入处理器。授权需要的就这些。

#### 注册授权模块

在根模块中，把 `AuthorizationModule` 与 `AuthenticationModule` 并列导入。`AuthenticationModule` 的注册方式与身份验证教程一致，带上 `accessToken` 选项；`JwtAuth` 则是 `AuthModule` 的提供者：

```typescript

import { Module } from '@nestjs/common';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { AuthModule } from './auth/auth.module.js';

@Module({
  imports: [
    // 身份验证放前面：它的守卫会设置 request.user，供授权读取。
    AuthenticationModule.forRootAsync({
      useFactory: () => ({
        accessToken: {
          key: process.env.JWT_SECRET!,
          issuer: 'https://api.example.com',
          audience: 'mobile-app',
          ttl: '15m',
        },
      }),
    }),
    AuthorizationModule.forRoot(),
    AuthModule,
  ],
})
export class AppModule {}
```

`forRoot()` 会把该模块注册为全局模块，它做三件事：

- 提供 `AuthorizationService`，在需要检查权限的代码处注入它即可。
- 把 `AuthorizationGuard` 注册为全局守卫。该守卫负责执行你下一步要加的 `@Can()` 装饰器，并且**默认拒绝**：处理器只有声明了检查才会运行——用 `@Can()`、用 `@Can.Anyone()`，或用 `@nestjs/authentication` 的 `@Public()`（后者等同于 `@Can.Anyone()`）。`POST /auth/token` 标了 `@Public()`，因此照常可用。
- 把服务内部报告的拒绝转换成 401 或 403，规则见[区分访客与无权用户，并暴露权限](/security/authorization#tell-guests-from-forbidden-users-and-expose-permissions)。

因此，漏写 `@Can()` 的路由是被关上的，而不是敞开的。启动时，该模块会把所有将因此被拒绝的处理器打印进日志，这份清单就是你做迁移的起点。完整规则见[参考](/security/authorization#what-a-route-declares)。

两个包都会注册全局守卫，**导入顺序因此很关键**。Nest 按扫描模块的顺序执行全局守卫，所以 `AuthenticationModule` 必须放在前面。若顺序颠倒，授权守卫会在任何东西设置 `request.user` 之前运行，于是每次 `@Can()` 检查看到的都是访客，已登录的员工访问仅限员工的路由时会拿到 401。`AuthorizationModule` 会在启动时检查顺序：它依靠守卫携带的标记识别 `AuthenticationGuard`；一旦该守卫排在后面，应用就拒绝启动，报错信息会同时点名这两个守卫并给出修正办法。

> warning **警告** 其他身份验证守卫（例如 Passport `AuthGuard()` 的子类）不携带这种标记，检查只能退而依据它们的类名。顺序错误时，它只记录一条错误日志，应用照常启动，而每次 `@Can()` 检查都把已登录用户当作访客。这类守卫请用 `APP_GUARD` 注册，不要用 `app.useGlobalGuards()`：通过后一种方式添加的守卫，Nest 会排在所有 `APP_GUARD` 之后执行，于是它们总是位于授权守卫之后，检查也就看不到它们。

> info **提示** 守卫从 `request.user` 读取用户，在 WebSocket、微服务和 GraphQL 中则从对应位置读取。配合 `@nestjs/authentication` 时，在 WebSocket 或 `graphql-ws` 连接上，取到的是每条消息/每次操作的用户，而非连接本身的用户，详见[参考](/security/authorization#reference)。如果你的身份验证把用户存放在别处，请给 `forRoot()` 传入一个 `getUser` 函数；若它需要依赖某个提供者，则改由 `forRootAsync()` 的工厂返回。如果你用 `@UseGuards()` 而非全局守卫完成身份验证，请传 `globalGuard: false`，并把 `AuthorizationGuard` 排在身份验证守卫之后。

#### 为商品编写策略

商品同样是普通对象，以 slug 作为标识、以分为单位计价，与身份验证教程一致：

```typescript

export interface Product {
  /** slug，例如 `salmon-kibble-2kg`。 */
  id: string;
  name: string;
  /** 以分为单位。 */
  price: number;
  published: boolean;
}

export type ProductInput = Omit<Product, 'id'>;
```

策略是用 `@Policy()` 装饰的类。凡是首参为「用户」、返回 `boolean` 或 `Promise<boolean>` 的方法，都是一个**能力**（ability）。只有字面量 `true` 表示放行；其他任何返回值都表示拒绝，即便是真值（truthy）也不行。

```typescript

import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import type { Product } from './product.js';

const isStaff = (user: User | null) => !!user?.roles.includes('staff');

@Policy()
export class ProductPolicy {
  // `null` 表示访客。所有人都能看到已发布商品；员工还能看到草稿。
  view(user: User | null, product: Product) {
    return product.published || isStaff(user);
  }

  viewDrafts(user: User | null) {
    return isStaff(user);
  }

  create(user: User | null) {
    return isStaff(user);
  }

  update(user: User | null) {
    return isStaff(user);
  }
}
```

用户参数写成什么类型，本身就是一种决策。写成 `User | null`，意味着该能力对访客也会执行——访客以 `null` 的身份进来。访客可以浏览商品目录，所以这里每个能力都接受 `null`，`view` 与 `viewDrafts` 也都能给访客一个真实答案。

`ProductsService` 以两种方式使用策略。`can()` 返回 `true` 或 `false`，这里用来决定列表是否包含草稿；`authorize()` 在能力拒绝时抛出异常，因此 `findOne()` 绝不会把草稿返回给无权查看的人。

```typescript

import { Injectable, NotFoundException } from '@nestjs/common';
import { AuthorizationService } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import type { Product, ProductInput } from './product.js';
import { ProductPolicy } from './product.policy.js';

@Injectable()
export class ProductsService {
  // 代替你的商品数据表。
  private readonly products: Product[] = [
    { id: 'salmon-kibble-2kg', name: 'Salmon kibble, 2 kg', price: 2499, published: true },
    { id: 'clumping-litter-10l', name: 'Clumping litter, 10 l', price: 1599, published: true },
    { id: 'heated-cat-bed', name: 'Heated cat bed', price: 5499, published: false },
  ];

  constructor(private readonly authorizationService: AuthorizationService) {}

  async findAll(user: User | null) {
    const withDrafts = await this.authorizationService.can(ProductPolicy, 'viewDrafts', user);
    return withDrafts ? this.products : this.products.filter((product) => product.published);
  }

  async findOne(user: User | null, id: string) {
    const product = this.find(id);
    await this.authorizationService.authorize(ProductPolicy, 'view', user, product);
    return product;
  }

  create(input: ProductInput) {
    const product = { ...input, id: slug(input.name) };
    this.products.push(product);
    return product;
  }

  update(id: string, changes: Partial<ProductInput>) {
    return Object.assign(this.find(id), changes);
  }

  remove(id: string) {
    this.products.splice(this.products.indexOf(this.find(id)), 1);
  }

  private find(id: string) {
    const product = this.products.find((product) => product.id === id);
    if (!product) {
      throw new NotFoundException();
    }
    return product;
  }
}

/** `Sisal scratching post` → `sisal-scratching-post`。 */
const slug = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
```

新建和更新商品并不依赖某条具体记录，所以这类检查放在路由上。这些路由的请求体是 DTO，写成类或 Zod schema 均可；更新操作接受新产品字段的任意子集：

```typescript

import { PartialType } from '@nestjs/mapped-types';
import { IsBoolean, IsPositive, IsString, MinLength } from 'class-validator';

export class CreateProductDto {
  @IsString()
  @MinLength(1)
  name: string;

  @IsPositive()
  price: number;

  @IsBoolean()
  published: boolean;
}

/** 上面字段的任意子集。 */
export class UpdateProductDto extends PartialType(CreateProductDto) {}
```

```typescript

import { z } from 'zod';

export const createProductSchema = z.object({
  name: z.string().min(1),
  price: z.number().positive(),
  published: z.boolean(),
});
export type CreateProductDto = z.infer<typeof createProductSchema>;

/** 上面字段的任意子集。 */
export const updateProductSchema = createProductSchema.partial();
export type UpdateProductDto = z.infer<typeof updateProductSchema>;
```

`@Can(ProductPolicy, 'create')` 会让守卫在处理器运行之前调用 `create(user)`：

```typescript

import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { Authenticate, CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import { ProductPolicy } from './product.policy.js';
import { CreateProductDto, UpdateProductDto } from './products.dto.js';
import { ProductsService } from './products.service.js';

@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Get()
  @Authenticate({ optional: true })
  @Can.Anyone()
  findAll(@CurrentUser() user: User | null) {
    return this.productsService.findAll(user);
  }

  @Get(':id')
  @Authenticate({ optional: true })
  @Can.Anyone()
  findOne(@CurrentUser() user: User | null, @Param('id') id: string) {
    return this.productsService.findOne(user, id);
  }

  @Post()
  @Can(ProductPolicy, 'create')
  create(@Body() input: CreateProductDto) {
    return this.productsService.create(input);
  }

  @Patch(':id')
  @Can(ProductPolicy, 'update')
  update(@Param('id') id: string, @Body() changes: UpdateProductDto) {
    return this.productsService.update(id, changes);
  }
}
```

改用 Zod schema 时，body 参数声明的是 schema 而非类：

```typescript

import { createProductSchema, updateProductSchema, type CreateProductDto, type UpdateProductDto } from './products.schemas.js';
// ...
@Post()
@Can(ProductPolicy, 'create')
create(@Body({ schema: createProductSchema }) input: CreateProductDto) {
  return this.productsService.create(input);
}

@Patch(':id')
@Can(ProductPolicy, 'update')
update(@Param('id') id: string, @Body({ schema: updateProductSchema }) changes: UpdateProductDto) {
  return this.productsService.update(id, changes);
}
```

某条路由是否允许访客进入，由身份验证决定，而不是策略。读接口使用带 `optional: true` 的 `@Authenticate()`：带有效令牌的请求会得到对应用户，没有令牌的请求则以 `null` 继续，`@CurrentUser()` 注入的正是这个值。若不加该装饰器，访客会在任何策略执行之前先收到 401；若改用 `@Public()`，身份验证会完全忽略令牌，于是 Sam 也只能以访客身份浏览，永远看不到草稿。

读接口把检查放在服务里，因此声明 `@Can.Anyone()`：凡是身份验证放行的人都可以调用，具体看到什么由 `ProductsService` 决定。不声明的话，守卫会直接拒绝它们。

`@Can()` 会做类型检查，能力名拼错就通不过编译：

```typescript
@Post()
@Can(ProductPolicy, 'craete')
// error TS2345: Argument of type '"craete"' is not assignable to parameter of type '"create" | "update" | "view" | "viewDrafts"'.
create(@Body() input: CreateProductDto) {}
```

错误信息会列出可以挂在路由上的能力，也就是那些用户参数接受 `null` 的能力——守卫无从得知某条路由是否有用户。`view` 属于这一类，但 `@Can(ProductPolicy, 'view')` 依然通不过编译（`Expected 3 arguments, but got 2`）：`view` 还要接收商品对象，而守卫手上没有可传的实例。需要具体记录的检查应放进服务，正如 `findOne()` 那样；只需要 URL 中 id 的检查则可以留在路由上，见[检查路由参数](/security/authorization#check-a-route-parameter)。

最后，把策略注册为所属功能模块的提供者：

```typescript

import { Module } from '@nestjs/common';
import { ProductPolicy } from './product.policy.js';
import { ProductsController } from './products.controller.js';
import { ProductsService } from './products.service.js';

@Module({
  controllers: [ProductsController],
  providers: [ProductsService, ProductPolicy],
})
export class ProductsModule {}
```

把 `ProductsModule` 加入 `AppModule` 的 `imports`。`@Policy()` 同时让该类可被注入；授权模块会发现应用中所有的策略提供者，无论它注册在哪个模块。另一种做法是通过 `AuthorizationModule.forRoot()` 的 `policies` 选项显式列出策略。

> info **提示** 如果某个 `@Can()` 指向了无人注册的策略，应用会拒绝启动，报错信息会指出是哪个处理器。

#### 逐条检查订单记录

订单沿用身份验证教程中的定义：它通过 `userId` 归属于某位顾客，并在一组状态之间流转：

```typescript

export interface OrderItem {
  productId: string;
  quantity: number;
}

export interface Order {
  id: string;
  userId: string;
  items: OrderItem[];
  /** 以分为单位。 */
  total: number;
  status: 'pending' | 'paid' | 'shipped' | 'refunded';
}
```

Alice 能否查看 Bob 的某笔订单，取决于那笔订单本身，所以这些能力把订单作为第二个参数：

```typescript

import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import type { Order } from './order.js';

@Policy()
export class OrderPolicy {
  viewAll(user: User) {
    return user.roles.includes('staff');
  }

  // 顾客只能看自己的订单；员工可以看所有人的订单。
  view(user: User, order: Order) {
    return order.userId === user.id || user.roles.includes('staff');
  }

  // 员工可以给已付款订单退款。待付款、已发货和已退款的订单
  // 任何人都不能退款。
  refund(user: User, order: Order) {
    return user.roles.includes('staff') && order.status === 'paid';
  }
}
```

这些能力接收的是 `User` 而非 `User | null`。订单相关路由都要求用户已登录，而只由服务内部调用的能力可以如实声明这一点；这样一来，编译器会要求调用方在校验之前先排除「用户不存在」的情形。

四个演示订单代替订单表，id 与演示账号一样是固定的：Alice 有一笔已付款订单和一笔已发货订单，Bob 有一笔购买五袋三文鱼粮的已付款订单（124.95，这个金额在[策略注入服务](/security/authorization#inject-a-service-into-a-policy)时会派上用场）和一笔待付款订单：

```typescript

import { alice, bob } from '../users/demo-users.js';
import type { Order } from './order.js';

/** 演示订单：Alice 有一笔已付款、一笔已发货，Bob 有一笔已付款、一笔待付款。 */
export const alicePaid: Order = {
  id: 'b69f25e7-db50-4abe-86d3-2ef2bd148009',
  userId: alice.id,
  items: [{ productId: 'salmon-kibble-2kg', quantity: 1 }],
  total: 2499,
  status: 'paid',
};

export const aliceShipped: Order = {
  id: 'd626a0c1-4122-4f83-ab7a-b009c26f35c7',
  userId: alice.id,
  items: [{ productId: 'clumping-litter-10l', quantity: 1 }],
  total: 1599,
  status: 'shipped',
};

export const bobPaid: Order = {
  id: '0ea8343b-879d-4b83-884b-6d5bb02f802f',
  userId: bob.id,
  items: [{ productId: 'salmon-kibble-2kg', quantity: 5 }],
  total: 12495,
  status: 'paid',
};

export const bobPending: Order = {
  id: '7e7023d3-cb2a-48d2-8c4e-20c07e6b8c06',
  userId: bob.id,
  items: [{ productId: 'clumping-litter-10l', quantity: 1 }],
  total: 1599,
  status: 'pending',
};

export const demoOrders = [alicePaid, aliceShipped, bobPaid, bobPending];
```

`OrdersService` 先加载订单，再针对它做授权：

```typescript

import { Injectable, NotFoundException } from '@nestjs/common';
import { AuthorizationService } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import { demoOrders } from './demo-orders.js';
import type { Order } from './order.js';
import { OrderPolicy } from './order.policy.js';

@Injectable()
export class OrdersService {
  // 代替你的订单表：这里存的是副本，因为退款会改变订单状态。
  private readonly orders: Order[] = demoOrders.map((order) => ({ ...order }));

  constructor(private readonly authorizationService: AuthorizationService) {}

  async findAll(user: User) {
    // 列表在查询中过滤；策略一次只检查一条记录。
    return (await this.authorizationService.can(OrderPolicy, 'viewAll', user))
      ? this.orders
      : this.orders.filter((order) => order.userId === user.id);
  }

  async findOne(user: User, id: string) {
    const order = this.find(id);
    await this.authorizationService.authorize(OrderPolicy, 'view', user, order);
    return order;
  }

  async refund(user: User, id: string) {
    const order = this.find(id);
    await this.authorizationService.authorize(OrderPolicy, 'refund', user, order);
    // 在这里通过支付服务商完成退款，然后记录结果。
    order.status = 'refunded';
    return order;
  }

  private find(id: string) {
    const order = this.orders.find((order) => order.id === id);
    if (!order) {
      throw new NotFoundException();
    }
    return order;
  }
}
```

策略类之后的一切，都由能力签名推导类型：能力名、用户和订单。能力名拼错、漏传订单、传入的对象不是 `Order`，或者用户可能为 `null`，都通不过编译：

```typescript
async show(user: User | null, order: Order) {
  await this.authorizationService.authorize(OrderPolicy, 'view', user, order);
  // error TS2345: Argument of type 'User | null' is not assignable to parameter of type 'User'.
}
```

列表不会逐条检查订单。它问的是一个查询能直接利用的问题——「该用户能否看到全部订单？」——然后在数据库层过滤。若先把所有记录取出再逐行检查，既会拉取过多数据，也会破坏分页。

把检查放在服务而不是控制器里，意味着所有调用方遵循同一套规则：无论调用者是控制器、GraphQL 解析器，还是处理退款请求的队列 worker。

控制器把已登录用户一路传下去。身份验证教程里的 `OrdersService` 是从 `AuthenticationContext` 读取用户的；这里改成参数，于是服务签名本身就说明了「这次检查针对谁」，队列 worker 也能就指定用户调用它。每条路由都在服务里检查，因此都声明 `@Can.Anyone()`：

```typescript

import { Controller, Get, HttpCode, Param, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import { OrdersService } from './orders.service.js';

@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Get()
  @Can.Anyone()
  findAll(@CurrentUser() user: User) {
    return this.ordersService.findAll(user);
  }

  @Get(':id')
  @Can.Anyone()
  findOne(@CurrentUser() user: User, @Param('id') id: string) {
    return this.ordersService.findOne(user, id);
  }

  @Post(':id/refund')
  @HttpCode(200)
  @Can.Anyone()
  refund(@CurrentUser() user: User, @Param('id') id: string) {
    return this.ordersService.refund(user, id);
  }
}
```

```typescript

import { Module } from '@nestjs/common';
import { OrderPolicy } from './order.policy.js';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';

@Module({
  controllers: [OrdersController],
  providers: [OrdersService, OrderPolicy],
})
export class OrdersModule {}
```

把 `OrdersModule` 加入 `AppModule` 的 `imports`。现在 Alice 从 `GET /orders` 只能拿到自己的两笔订单，而访问 Bob 的某笔订单详情 `GET /orders/:id` 会得到 403。

> info **提示** 403 等于确认「该订单确实存在」。如果这一点需要避免（例如 id 连续、可以被猜出），请改用 `can()` 判断，并抛出 `NotFoundException`。

#### 检查路由参数

有些检查需要参数，却不需要具体记录。员工通过 `GET /customers/:customerId/orders` 查询某位顾客的订单，顾客也可以在这里列出自己的订单。Alice 能否调用它，仅取决于 URL 里的那个 id，因此检查之前无需加载任何数据。给 `OrderPolicy` 补一个能力：

```typescript

// 顾客列出自己的订单；员工可以列出任何人的。访客一律拒绝。
viewOrdersOf(user: User | null, customerId: string) {
  return !!user && (user.id === customerId || user.roles.includes('staff'));
}
```

与 `OrderPolicy` 的其他能力不同，这个能力接收 `User | null`，因为用在路由上的能力必须能接受访客。路由用 `@Can()` 调用它，其第三个参数负责从调用中取出「用户之后的那些参数」：

```typescript

import { Controller, Get, Param } from '@nestjs/common';
import { Can } from '@nestjs/authorization';
import { OrderPolicy } from './order.policy.js';
import { OrdersService } from './orders.service.js';

@Controller('customers/:customerId/orders')
export class CustomerOrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Get()
  @Can(OrderPolicy, 'viewOrdersOf', (context) => [context.switchToHttp().getRequest().params.customerId])
  findAll(@Param('customerId') customerId: string) {
    return this.ordersService.findByCustomer(customerId);
  }
}
```

`OrdersService` 新增一个按顾客过滤的方法，它自身不做检查，因为检查已在路由上完成：

```typescript

findByCustomer(customerId: string) {
  return this.orders.filter((order) => order.userId === customerId);
}
```

把这个控制器加入 `OrdersModule` 的 `controllers`。现在 Alice 访问 `GET /customers/<Alice 的 id>/orders` 能得到自己的订单，访问 Bob 的则得到 403；Sam 两者都能看；访客得到 401。

该函数的类型由能力自身的参数推导。当能力除了用户还接收别的参数时，省略这个函数就通不过编译；返回类型不对同样通不过：

```typescript
@Get()
@Can(OrderPolicy, 'viewOrdersOf')
// error TS2554: Expected 3 arguments, but got 2.
findAll() {}

@Get()
@Can(OrderPolicy, 'viewOrdersOf', () => [42])
// error TS2322: Type 'number' is not assignable to type 'string'.
findAll() {}
```

它在守卫中执行，早于任何管道，因此拿到的值是传输层原样送来的：路由参数仍是字符串，什么都还没校验。`customerId` 上的 `ParseUUIDPipe` 会在检查之后才运行，所以用户无权查看的 id 得到的是 403 而不是 400。函数抛出的错误（例如参数缺失时抛 `BadRequestException`）会原样送达 HTTP 客户端。在 WebSocket 和微服务里，任何守卫抛出的 `HttpException`（包括这个函数）都会被 Nest 报告为内部错误，因此那里应抛 `WsException` 或 `RpcException`。拒绝事件会在其 `args` 中带上该函数读取到的值。

传标识符和作用域，不要传记录。在守卫里加载订单会导致加载两次——一次为检查、一次在处理器中——而且会在处理器来得及回答 404 之前先给出 403。这正是 `GET /orders/:id` 改在服务里检查的原因。

单独声明的函数返回的是数组，而不是能力参数所描述的那个元组，因此结尾要加 `as const`。这样就能写一个小工具函数，在多条路由间复用：

```typescript

import type { ExecutionContext } from '@nestjs/common';

/** 为 `@Can()` 读取一个路由参数。 */
export const param = (name: string) => (context: ExecutionContext) =>
  [context.switchToHttp().getRequest().params[name] as string] as const;
```

```typescript
@Can(OrderPolicy, 'viewOrdersOf', param('customerId'))
```

其他传输方式下，请从各自的上下文读取参数：GraphQL 操作的参数用 `GqlExecutionContext.create(context).getArgs()`，WebSocket 消息用 `context.switchToWs().getData()`，微服务消息用 `context.switchToRpc().getData()`。

#### 用 `before()` 让管理员直接放行

管理员可以任意处置商品目录，包括删除商品，而其他任何人都不能删。与其给每个能力都加上管理员判断，不如给策略一个 `before()` 钩子：

```typescript

import { Policy, type PolicyBefore } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import type { Product } from './product.js';

const isStaff = (user: User | null) => !!user?.roles.includes('staff');

@Policy()
export class ProductPolicy implements PolicyBefore<User> {
  // 管理员可通过下面所有检查，包括以后新增的能力。
  before(user: User | null) {
    if (user?.roles.includes('admin')) {
      return true;
    }
  }

  // `null` 表示访客。所有人都能看到已发布商品；员工还能看到草稿。
  view(user: User | null, product: Product) {
    return product.published || isStaff(user);
  }

  viewDrafts(user: User | null) {
    return isStaff(user);
  }

  create(user: User | null) {
    return isStaff(user);
  }

  update(user: User | null) {
    return isStaff(user);
  }

  // 除管理员之外无人可用——管理员已在 before() 中被放行。
  delete(_user: User | null) {
    return false;
  }
}
```

`before()` 会在所属策略的每个能力之前运行，路由上的检查和服务里的检查皆然。它接收用户、能力名以及该能力的参数。返回 `true` 即放行，返回 `false` 即拒绝，什么也不返回则交由能力自己判断。访客同样会进到 `before()`，因此它的用户参数必须接受 `null`。无论类是否实现了 `PolicyBefore<User>`，`before(user: User)` 都通不过编译。

把使用新能力的路由加到 `ProductsController`，并从 `@nestjs/common` 导入 `Delete` 与 `HttpCode`：

```typescript

@Delete(':id')
@HttpCode(204)
@Can(ProductPolicy, 'delete')
remove(@Param('id') id: string) {
  this.productsService.remove(id);
}
```

现在 Sam 调用 `DELETE /products/clumping-litter-10l` 会得到 403，Ada 则得到 204。

> warning **警告** `before()` 会跳过所属策略的全部能力，包括那些本应对所有人生效的规则。这正是 `OrderPolicy` 不设管理员旁路的原因：「已发货订单任何人都不能退款」对 Ada 也必须成立。如果某个策略两者都要，请检查 `before()` 收到的能力名，对不该跳过的能力返回空值。实现 `PolicyBefore<User, Ability<OrderPolicy>>` 并把能力名标注为 `Ability<OrderPolicy>`，这样排除项写错就通不过编译。

#### 向策略注入服务

财务对每位员工的单人退款额度设了上限：默认 100.00，个别人更高。这些上限存在策略之外，放在某个会读取数据表或配置服务的地方：

```typescript

import { Injectable } from '@nestjs/common';
import { ada } from '../users/demo-users.js';
import type { User } from '../users/user.js';

@Injectable()
export class RefundLimitsService {
  // 财务设定的按人限额，以分为单位，按用户 id 索引。代替数据表或配置服务。
  private readonly limits = new Map<string, number>([[ada.id, 100_000]]);

  async maxRefundFor(user: User): Promise<number> {
    return this.limits.get(user.id) ?? 10_000;
  }
}
```

由于策略就是提供者，它可以通过构造函数注入该服务。`refund` 能力随之变为 `async`：

```typescript

import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import type { Order } from './order.js';
import { RefundLimitsService } from './refund-limits.service.js';

@Policy()
export class OrderPolicy {
  constructor(private readonly refundLimitsService: RefundLimitsService) {}

  viewAll(user: User) {
    return user.roles.includes('staff');
  }

  // 顾客只能看自己的订单；员工可以看所有人的订单。
  view(user: User, order: Order) {
    return order.userId === user.id || user.roles.includes('staff');
  }

  // 顾客列出自己的订单；员工可以列出任何人的。访客一律拒绝。
  viewOrdersOf(user: User | null, customerId: string) {
    return !!user && (user.id === customerId || user.roles.includes('staff'));
  }

  // 员工可以给已付款订单退款，金额不超其限额。待付款、已发货和
  // 已退款的订单任何人都不能退款。
  async refund(user: User, order: Order) {
    if (!user.roles.includes('staff') || order.status !== 'paid') {
      return false;
    }
    return order.total <= (await this.refundLimitsService.maxRefundFor(user));
  }
}
```

`authorize()`、`can()` 和守卫都会等待异步能力的结果，所以 `OrdersService` 无需改动。把该服务与策略注册在一起：

```typescript

import { Module } from '@nestjs/common';
import { CustomerOrdersController } from './customer-orders.controller.js';
import { OrderPolicy } from './order.policy.js';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';
import { RefundLimitsService } from './refund-limits.service.js';

@Module({
  controllers: [OrdersController, CustomerOrdersController],
  providers: [OrdersService, OrderPolicy, RefundLimitsService],
})
export class OrdersModule {}
```

由于 `OrderPolicy` 注册在 `OrdersModule` 中，它能注入该模块的提供者。而通过 `forRoot()` 的 `policies` 选项列出的策略，实际上活在授权模块里，需要借助 `imports` 选项才能拿到自己的依赖。

Bob 那笔已付款订单金额为 124.95。Sam（限额 100.00）尝试退款时得到 403，Ada（限额 1,000.00）则成功。

> warning **警告** 策略必须是单例。请求作用域或瞬态（transient）的策略，以及依赖了请求作用域提供者的策略，都会在启动时抛错。不要让策略持有与单个请求相关的状态，能力需要什么就以参数传入。

#### 区分访客与无权用户，并暴露权限

被拒绝的请求会得到 401 或 403，取决于请求者是谁、请求发生在哪里：

| 调用方     | 路由                                                                   | 状态码                                               | 来源                     |
| ---------- | ---------------------------------------------------------------------- | ---------------------------------------------------- | ------------------------ |
| 访客       | 需要登录（默认情况），例如 `POST /products` 或 `GET /orders`           | 401，并带 `WWW-Authenticate: Bearer realm="store"`   | 身份验证，在任何策略执行之前 |
| 访客       | 可选身份验证，且策略拒绝 `null`，例如查看草稿商品                      | 401                                                  | 授权                     |
| 已登录用户 | 策略拒绝，例如 Alice 调用 `POST /products`，或访问 Bob 的订单          | 403                                                  | 授权                     |

授权从不决定某条路由是否需要用户，那是身份验证的职责。当策略拒绝的是访客时，该包回答 401（「请先登录再试」）而不是 403（「永远不行」），因为登录之后答案可能就变了。

`authorize()` 自身抛出的是 `AuthorizationError`：它的 `reason` 为 `unauthenticated` 或 `forbidden`，`status` 则是相应的 401 或 403。它不是 HTTP 异常，因为同一个服务也会跑在队列 worker 和 WebSocket 网关里。当这个错误离开处理器时，`AuthorizationModule` 会把它转换成守卫所抛的 `UnauthorizedException` 或 `ForbiddenException`，响应体保持一致，因此异常过滤器和客户端可以像处理其他 HTTP 错误一样处理二者。在 WebSocket 网关和微服务处理器中，它则转换为 `WsException` 或 `RpcException`。403 的响应体不会点出具体是哪个能力。

`can()` 在被拒绝时从不抛错。无论访客还是无权用户，它都返回 `false`，因此它是「塑造响应内容」的利器。给每笔订单加一个 `canRefund` 标记，前端据此决定是否显示退款按钮，而不必重复实现一遍规则：

```typescript

import { Injectable, NotFoundException } from '@nestjs/common';
import { AuthorizationService } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import { demoOrders } from './demo-orders.js';
import type { Order } from './order.js';
import { OrderPolicy } from './order.policy.js';

export type OrderView = Order & { canRefund: boolean };

@Injectable()
export class OrdersService {
  // 代替你的订单表：这里存的是副本，因为退款会改变订单状态。
  private readonly orders: Order[] = demoOrders.map((order) => ({ ...order }));

  constructor(private readonly authorizationService: AuthorizationService) {}

  async findAll(user: User): Promise<OrderView[]> {
    // 列表在查询中过滤；策略一次只检查一条记录。
    const orders = (await this.authorizationService.can(OrderPolicy, 'viewAll', user))
      ? this.orders
      : this.orders.filter((order) => order.userId === user.id);
    return Promise.all(orders.map((order) => this.toView(user, order)));
  }

  async findOne(user: User, id: string): Promise<OrderView> {
    const order = this.find(id);
    await this.authorizationService.authorize(OrderPolicy, 'view', user, order);
    return this.toView(user, order);
  }

  async refund(user: User, id: string): Promise<OrderView> {
    const order = this.find(id);
    await this.authorizationService.authorize(OrderPolicy, 'refund', user, order);
    // 在这里通过支付服务商完成退款，然后记录结果。
    order.status = 'refunded';
    return this.toView(user, order);
  }

  private async toView(user: User, order: Order): Promise<OrderView> {
    return { ...order, canRefund: await this.authorizationService.can(OrderPolicy, 'refund', user, order) };
  }

  private find(id: string) {
    const order = this.orders.find((order) => order.id === id);
    if (!order) {
      throw new NotFoundException();
    }
    return order;
  }
}
```

这个标记出自与 `POST /orders/:id/refund` 完全相同的那条 `refund` 能力，所以按钮与接口不可能说法不一。Sam 看到 Alice 的已付款订单为 `canRefund: true`，看到 Bob 那笔（超出他的限额）为 `false`；Ada 两笔都是 `true`。

#### 动手试试

带上保存签名密钥的 `.env` 文件启动应用：

```bash
$ npm run start:dev -- --env-file .env
```

另开一个终端，分别以 Alice、Sam、Ada 的身份登录。`--json`（curl 7.82 及以上）直接发送带 JSON 请求体的 `POST`；`token` 辅助函数用 [jq](https://jqlang.org/) 取出访问令牌：

```bash
$ token() { curl -s localhost:3000/auth/token --json "{\"email\":\"$1@example.com\",\"password\":\"catnip4all\"}" | jq -r .accessToken; }
$ ALICE=$(token alice) SAM=$(token sam) ADA=$(token ada)
```

访客只能看到已发布商品，员工还能看到草稿：

```bash
$ curl localhost:3000/products
[{"id":"salmon-kibble-2kg","name":"Salmon kibble, 2 kg","price":2499,"published":true},{"id":"clumping-litter-10l","name":"Clumping litter, 10 l","price":1599,"published":true}]

$ curl -s localhost:3000/products -H "Authorization: Bearer $SAM" | jq -c '.[] | {id, published}'
{"id":"salmon-kibble-2kg","published":true}
{"id":"clumping-litter-10l","published":true}
{"id":"heated-cat-bed","published":false}
```

草稿商品本身，对访客返回 401，对顾客返回 403。以下（及后文）的响应头均做了删减：

```bash
$ curl -i localhost:3000/products/heated-cat-bed
HTTP/1.1 401 Unauthorized
{"message":"Unauthorized","statusCode":401}

$ curl -i localhost:3000/products/heated-cat-bed -H "Authorization: Bearer $ALICE"
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}
```

只有员工可以新增商品。访客被身份验证拦下，Alice 被 `@Can()` 拦下：

```bash
$ curl -i localhost:3000/products --json '{"name":"Sisal scratching post","price":3999,"published":false}'
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="store"
{"message":"Unauthorized","statusCode":401}

$ curl -i localhost:3000/products -H "Authorization: Bearer $ALICE" --json '{"name":"Sisal scratching post","price":3999,"published":false}'
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}

$ curl localhost:3000/products -H "Authorization: Bearer $SAM" --json '{"name":"Sisal scratching post","price":3999,"published":false}'
{"name":"Sisal scratching post","price":3999,"published":false,"id":"sisal-scratching-post"}
```

Alice 只能看到自己的订单，且两笔都不能退款。Sam 能看到全部订单，`canRefund` 按他自己的权限计算。Bob 的已付款订单对 Alice 是不可越界的：

```bash
$ curl -s localhost:3000/orders -H "Authorization: Bearer $ALICE" | jq -c '.[] | {id, status, canRefund}'
{"id":"b69f25e7-db50-4abe-86d3-2ef2bd148009","status":"paid","canRefund":false}
{"id":"d626a0c1-4122-4f83-ab7a-b009c26f35c7","status":"shipped","canRefund":false}

$ curl -s localhost:3000/orders -H "Authorization: Bearer $SAM" | jq -c '.[] | {id, status, total, canRefund}'
{"id":"b69f25e7-db50-4abe-86d3-2ef2bd148009","status":"paid","total":2499,"canRefund":true}
{"id":"d626a0c1-4122-4f83-ab7a-b009c26f35c7","status":"shipped","total":1599,"canRefund":false}
{"id":"0ea8343b-879d-4b83-884b-6d5bb02f802f","status":"paid","total":12495,"canRefund":false}
{"id":"7e7023d3-cb2a-48d2-8c4e-20c07e6b8c06","status":"pending","total":1599,"canRefund":false}

$ curl -i localhost:3000/orders/0ea8343b-879d-4b83-884b-6d5bb02f802f -H "Authorization: Bearer $ALICE"
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}
```

Sam 能给 Alice 的已付款订单退款，但退不了她那笔已发货的订单，也退不了 Bob 那笔（超出他的限额）。Ada 同样退不了已发货订单，但 Bob 那笔在她的限额之内：

```bash
$ curl -s -X POST localhost:3000/orders/b69f25e7-db50-4abe-86d3-2ef2bd148009/refund -H "Authorization: Bearer $SAM" | jq -c '{id, status, canRefund}'
{"id":"b69f25e7-db50-4abe-86d3-2ef2bd148009","status":"refunded","canRefund":false}

$ curl -i -X POST localhost:3000/orders/d626a0c1-4122-4f83-ab7a-b009c26f35c7/refund -H "Authorization: Bearer $SAM"
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}

$ curl -i -X POST localhost:3000/orders/0ea8343b-879d-4b83-884b-6d5bb02f802f/refund -H "Authorization: Bearer $SAM"
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}

$ curl -i -X POST localhost:3000/orders/d626a0c1-4122-4f83-ab7a-b009c26f35c7/refund -H "Authorization: Bearer $ADA"
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}

$ curl -s -X POST localhost:3000/orders/0ea8343b-879d-4b83-884b-6d5bb02f802f/refund -H "Authorization: Bearer $ADA" | jq -c '{id, status, canRefund}'
{"id":"0ea8343b-879d-4b83-884b-6d5bb02f802f","status":"refunded","canRefund":false}
```

只有管理员能删除商品：

```bash
$ curl -i -X DELETE localhost:3000/products/clumping-litter-10l -H "Authorization: Bearer $SAM"
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}

$ curl -i -X DELETE localhost:3000/products/clumping-litter-10l -H "Authorization: Bearer $ADA"
HTTP/1.1 204 No Content
```

#### 测试

端到端测试会启动整个应用、通过真实端点登录，并在 HTTP 层检验规则。与身份验证教程一样，scrypt 的慢是刻意设计的，因此测试用一个更廉价的 `PasswordHasher` 覆盖它；同时应用会在启动时读取 `JWT_SECRET`，所以测试配置里要提供一个：

```typescript

export default defineConfig({
  // ...
  test: {
    // ...
    env: {
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
    },
  },
});
```

```typescript

import type { INestApplication } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { AppModule } from '../src/app.module.js';
import { alicePaid, aliceShipped, bobPaid } from '../src/orders/demo-orders.js';

describe('Orders (e2e)', () => {
  let app: INestApplication;

  const signIn = async (email: string) => {
    const { body } = await request(app.getHttpServer())
      .post('/auth/token')
      .send({ email, password: 'catnip4all' })
      .expect(200);
    return `Bearer ${body.accessToken}`;
  };

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      // scrypt 的慢是刻意的；测试没必要陪着慢。
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 11 }))
      .compile();
    app = moduleRef.createNestApplication();
    await app.listen(0, '127.0.0.1');
  });

  afterAll(() => app.close());

  it('asks guests to sign in', async () => {
    await request(app.getHttpServer()).get('/orders').expect(401);
  });

  it('shows customers only their own orders', async () => {
    const alice = await signIn('alice@example.com');
    const { body } = await request(app.getHttpServer())
      .get('/orders')
      .set('Authorization', alice)
      .expect(200);
    expect(body.map((order: { id: string }) => order.id)).toEqual([alicePaid.id, aliceShipped.id]);

    await request(app.getHttpServer()).get(`/orders/${bobPaid.id}`).set('Authorization', alice).expect(403);
  });

  it('lets staff refund a paid order once, within their limit', async () => {
    const sam = await signIn('sam@example.com');
    const refund = (id: string) =>
      request(app.getHttpServer()).post(`/orders/${id}/refund`).set('Authorization', sam);

    await refund(alicePaid.id).expect(200);
    await refund(alicePaid.id).expect(403); // 已退款
    await refund(aliceShipped.id).expect(403); // 已发货
    await refund(bobPaid.id).expect(403); // 超出 Sam 的限额
  });
});
```

策略就是普通类，因此不依赖 Nest 也能轻松做单元测试。自己构造策略实例、自行掌控它的依赖即可；演示账号和演示订单正好充当 fixture：

```typescript

import { vi } from 'vitest';
import { alice, sam } from '../users/demo-users.js';
import { alicePaid, bobPaid } from './demo-orders.js';
import { OrderPolicy } from './order.policy.js';
import { RefundLimitsService } from './refund-limits.service.js';

describe('OrderPolicy', () => {
  // 这里不用 Nest：策略就是个类，自己 new 出来即可。
  const refundLimits = new RefundLimitsService();
  const policy = new OrderPolicy(refundLimits);

  it('shows customers only their own orders', () => {
    expect(policy.view(alice, alicePaid)).toBe(true);
    expect(policy.view(alice, bobPaid)).toBe(false);
    expect(policy.view(sam, bobPaid)).toBe(true);
  });

  it('lets staff refund paid orders up to their limit', async () => {
    vi.spyOn(refundLimits, 'maxRefundFor').mockResolvedValue(5000);

    expect(await policy.refund(sam, { ...alicePaid, total: 5000 })).toBe(true);
    expect(await policy.refund(sam, { ...alicePaid, total: 5001 })).toBe(false);
    expect(await policy.refund(alice, alicePaid)).toBe(false);
  });

  it('refuses refunds on orders that are not paid', async () => {
    for (const status of ['pending', 'shipped', 'refunded'] as const) {
      expect(await policy.refund(sam, { ...alicePaid, status })).toBe(false);
    }
  });
});
```

直接调用能力会绕过 `before()`。钩子本身也只是一个方法，用同样的方式测它即可，例如 `expect(new ProductPolicy().before(ada)).toBe(true)`。要连带钩子与能力一起测，就走 `AuthorizationService`；若还要覆盖 401/403 的映射，就走 HTTP，正如端到端测试那样。

介于两者之间的还有服务层测试：使用真实的策略与 `AuthorizationModule`，不涉及 HTTP，也不做登录。在处理器之外，拒绝会保持为 `AuthorizationError`：

```typescript

import { Test } from '@nestjs/testing';
import { AuthorizationError, AuthorizationModule } from '@nestjs/authorization';
import { alice, sam } from '../users/demo-users.js';
import { alicePaid, bobPaid } from './demo-orders.js';
import { OrderPolicy } from './order.policy.js';
import { OrdersService } from './orders.service.js';
import { RefundLimitsService } from './refund-limits.service.js';

describe('OrdersService', () => {
  let orders: OrdersService;

  beforeEach(async () => {
    // 真实的策略与模块，不涉及 HTTP，也不做登录。
    const moduleRef = await Test.createTestingModule({
      imports: [AuthorizationModule.forRoot()],
      providers: [OrdersService, OrderPolicy, RefundLimitsService],
    }).compile();
    orders = moduleRef.get(OrdersService);
  });

  it("keeps Bob's order from Alice", async () => {
    await expect(orders.findOne(alice, bobPaid.id)).rejects.toThrow(AuthorizationError);
  });

  it('refunds within the limit only', async () => {
    await expect(orders.refund(sam, bobPaid.id)).rejects.toMatchObject({ reason: 'forbidden', ability: 'refund' });
    expect((await orders.refund(sam, alicePaid.id)).status).toBe('refunded');
  });
});
```

在更大的测试里替换策略，只需像替换普通提供者那样覆盖它，例如 `.overrideProvider(OrderPolicy).useValue(...)`：路由上的检查和服务里的检查都会针对覆盖后的实现运行。

#### 上线检查清单

- **让身份验证排在授权之前。** 使用 `AuthenticationModule` 时，导入顺序错误会让应用在启动阶段直接停下。换成其他身份验证守卫，则只会记录一条错误日志，因此请写一个端到端测试：登录并调用一条 `@Can()` 路由。有两种注册方式无论导入顺序如何都会排在授权守卫之后：请求作用域的 `APP_GUARD`（启动检查会指出这一点）和 `app.useGlobalGuards()`（检查看不到它）。请把身份验证注册为单例 `APP_GUARD`。
- **逐条复核每个 `@Can.Anyone()`。** 守卫会拒绝未声明任何检查的处理器，并在启动时逐个打印日志，所以漏写的 `@Can()` 只会让路由关着。而 `@Can.Anyone()` 会对所有通过身份验证的人敞开：请确认它的服务确实做了授权判断，或者这条路由本就不需要权限。针对 URL 中 id 的检查可以放在路由上，用 `@Can()` 的第三个参数传值——这样日后修改处理器也不会把它弄丢。
- **连接微服务时带上 `inheritAppConfig: true`。** 在混合应用中，只有 `connectMicroservice()` 拿到该选项时，Nest 才会在消息处理器上运行应用的全局守卫和拦截器。否则，消息处理器上的 `@Can()` 不会生效，`authorize()` 的拒绝也会以内部错误而非 401/403 的形式抵达调用方。
- **把记录级检查放进服务**，在加载记录之后执行，这样控制器、解析器和队列 worker 都能共用。
- **在需要检查记录的路由上，不要按 URL 缓存响应。** 像 Nest 的 `CacheInterceptor` 这样的缓存会在处理器运行之前就给出应答，于是可能把 Bob 的订单直接发给 Alice，而根本没问过 `OrderPolicy`。请把缓存放在检查之后，或按用户区分缓存。
- **在查询里过滤列表**：提一个查询能直接用上的问题（例如 `viewAll`），而不是把每一行都读出来再逐个检查。
- **写操作要重新校验状态。** 授权在退款之前读取订单，两个并发请求可能都看到 `paid`。请把写操作做成条件更新（只在状态仍为 `paid` 时才更新），并给支付服务商带上幂等键，这样重试也绝不会退两次款。
- **在 403 与 404 之间做出选择**：对于「是否存在」本身敏感的记录（例如 id 连续、可能被猜出的他人订单），需要考虑这一点。
- **保持策略无状态。** 它们是所有请求共享的单例。
- **留意 `can()` 标记的开销。** 每个标记都会对每一行运行一次能力，包括其中的异步操作。像退款限额这类较慢的查询请加缓存，或每个请求只取一次。
- **从配置中加载密钥。** JWT 密钥（至少 32 字节）请从密钥管理服务或 `ConfigService` 读取，不要写死在代码里。
- **在自己的守卫和中间件里用 `can()` 检查。** 它们在任何处理器之前运行，因此在那里抛出的 `AuthorizationError` 不会被转换成 401 或 403，而会变成 500。
- **审计拒绝事件。** 响应本身不会说明是哪个检查拒绝了调用方。订阅 `AuthorizationEvents`，为每次拒绝记录策略、能力与用户 id。每个事件都携带策略当时看到的用户与记录，请记录你需要的字段，而不是整个事件。

#### 参考

##### 模块选项

`AuthorizationModule.forRoot()` 接受以下选项。`forRootAsync()` 则在顶层（与 `useFactory` 并列）接受 `policies`、`imports`、`globalGuard` 和 `isGlobal`，而它的工厂函数返回 `getUser`。

| 选项 | 默认值 | 说明 |
| --- | --- | --- |
| `getUser` | `defaultGetUser` | 接收 `ExecutionContext` 并返回当前用户的函数，也可以返回其 Promise。参见[注册授权模块](/security/authorization#register-the-authorization-module)。 |
| `policies` | 无 | 要在授权模块自身注册的策略。任何模块中标注 `@Policy()` 的提供者都会被自动发现，无需列出。 |
| `imports` | 无 | `policies` 注入依赖时所用到的、导出这些提供者的模块。 |
| `globalGuard` | `true` | 把 `AuthorizationGuard` 注册为全局守卫。设为 `false` 时，用 `@UseGuards()` 把它排在身份验证守卫之后。 |
| `isGlobal` | `true` | 把该模块注册为全局模块。 |

`defaultGetUser` 从下列位置读取用户。`null`、`undefined` 和 `false` 都表示访客。

| 上下文 | 来源 |
| --- | --- |
| HTTP | `request.user` |
| GraphQL | 身份验证为该操作记录的用户；若没有，则取 GraphQL 上下文上的 `req.user` |
| WebSocket | 身份验证为该消息记录的用户；若没有，则取 `client.user`，再取 `client.data.user` |
| 微服务 | 传输上下文上的 `user`，从不取消息负载 |

WebSocket 客户端指的是连接，而不是单条消息；在 `graphql-ws` 之上，GraphQL 上下文里的 `req` 是该连接的升级请求，套接字上的每个操作都共享它。因此 `client.user` 与 `req.user` 保存的是最后完成认证的那条消息或那个操作的用户。`@nestjs/authentication` 还会在 client 和 `req` 上留下一个函数，键为 `Symbol.for('nestjs.authentication.userOf')`：它接收 `ExecutionContext`，返回该消息或该操作的用户——匿名的（即任何 `@Public()` 的）消息返回 `null`，无法判断时返回 `undefined`。`defaultGetUser` 会优先询问它。因此 `@Public()` 的消息或操作对 `@Can()` 而言就是访客，哪怕所在连接的握手曾经登录；被「全局登出」撤销的会话同样不再算数。如果自己写的 `getUser` 在这些传输方式下读取 `client.user` 或 `req.user`，拿到的会是连接最后使用的那个用户；其他身份验证包也可以留下同样的函数供查询。

##### 路由声明了什么

守卫依据处理器及其所在类声明了什么来做决定：

| 声明 | 守卫行为 |
| --- | --- |
| `@Can()` | 先执行类上的全部要求，再执行方法上的要求，全部通过才放行。 |
| `@Can.Anyone()` | 放行所有通过身份验证的人。 |
| 来自 `@nestjs/authentication` 的 `@Public()`（0.1.0 起） | 等同于 `@Can.Anyone()`。 |
| 什么也没声明 | 拒绝：已登录用户得 403，访客得 401。启动日志会点出该处理器。 |

在方法上，`@Can.Anyone()` 或 `@Public()` 会解除类级 `@Can()` 的约束，正如 `@Public()` 会解除类的身份验证一样。方法自身的 `@Can()` 依然生效，所以一个既标 `@Public()` 又标 `@Can()` 的方法仍会对访客执行检查。反过来，在类上，这两者都不会解除方法级 `@Can()`。在 `@Public()` 类中，被 `@Authenticate()` 重新纳入身份验证的方法并不公开，它需要自己单独声明。

在 Nest 不运行全局守卫的地方，什么都不会被拒绝：一是 GraphQL 字段解析器（除非 `fieldResolverEnhancers` 包含 `'guards'`），二是未带 `inheritAppConfig: true` 连接的混合应用的消息处理器。启用了该增强器后，每个 `@ResolveField()` 也需要声明；类级声明即可覆盖它们。

##### 事件

`AuthorizationEvents` 把所有拒绝通过 `events$` observable 暴露出来，同时发布到诊断通道（diagnostics channel）。`can()` 返回 `false` 不算拒绝，也不会发出任何事件。

| 事件类型 | 通道 | 触发时机 |
| --- | --- | --- |
| `denied` | `nestjs:authorization:denied` | `@Can()` 或 `authorize()` 拒绝了调用方 |

`AuthorizationDeniedEvent` 的负载包含以下字段：

- `type`：`'denied'`。
- `policy` 与 `ability`：拒绝发生的策略类名与能力名，例如 `OrderPolicy` 与 `refund`。当守卫因处理器未声明任何检查而拒绝时，两者均为 `null`。
- `reason`：访客为 `'unauthenticated'`，已登录用户为 `'forbidden'`。
- `user`：策略看到的用户，访客为 `null`。
- `args`：能力在用户之后的参数，例如记录本身。对 `@Can()` 而言，是其第三个参数读到的值；未提供则为空。
- `handler`：被 `@Can()` 保护的那个处理器，例如 `ProductsController.create`。`authorize()` 触发时没有该字段。

##### 错误

`authorize()` 抛出的 `AuthorizationError` 带有 `reason`、`status`、`policy` 和 `ability`。守卫因处理器未声明检查而拒绝时，携带的是同样的错误，只是 `policy` 与 `ability` 为 `null`。当它离开处理器时（或 `@Can()` 拒绝时），调用方拿到的是对应传输方式自己的错误，其响应体永远不点出策略或能力名。参见[区分访客与无权用户，并暴露权限](/security/authorization#tell-guests-from-forbidden-users-and-expose-permissions)。

| `reason` | `status` | HTTP | GraphQL `extensions.code` | WebSocket 与微服务 |
| --- | --- | --- | --- | --- |
| `unauthenticated` | 401 | `UnauthorizedException` | `UNAUTHENTICATED` | `WsException` 或 `RpcException`，带 `statusCode: 401` |
| `forbidden` | 403 | `ForbiddenException` | `FORBIDDEN` | `WsException` 或 `RpcException`，带 `statusCode: 403` |

在 `graphql-ws` 之上，客户端只能拿到错误消息（`Unauthorized` 或 `Forbidden`），没有 `extensions.code`：Apollo 驱动是在自己的错误格式化环节加上这些 code 的，而该环节在这种传输方式下不会执行。

在处理器之外抛出的 `AuthorizationError`（例如在你自己的守卫或中间件里）不会被映射，会直接变成 500。
