跳到主要内容

NestJS RBAC 教程:使用 Guard 实现基于角色的访问控制

本教程使用 node-casbin 为 NestJS API 添加基于角色的访问控制 (RBAC)。每个路由通过装饰器声明所需的权限,全局 guard 询问 Casbin 当前用户是否拥有该权限,并且角色可以相互继承,因此 admin 自动获得 editor 所能做的一切。

权限以资源和操作命名(articles, delete),而不是 URL 路径,这非常契合 NestJS 控制器。对于基于路径的规则,请参阅 Express 版本。

1. 安装​

从一个 NestJS 项目开始(nest new my-app)并添加 Casbin:

npm install casbin

2. 编写模型​

将其保存为项目根目录下的 model.conf:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
  • r = sub, obj, act:每个请求包含一个用户、一个资源和一个操作。
  • g = _, _:用户可以被分配给角色,角色也可以被分配给其他角色。
  • 当用户直接或间接通过继承的角色拥有策略规则中的角色时,g(r.sub, p.sub) 为真。

3. 编写策略​

将其保存为 policy.csv:

p, viewer, articles, read
p, editor, articles, create
p, editor, articles, update
p, admin, articles, delete

g, editor, viewer
g, admin, editor

g, alice, admin
g, bob, editor
g, carol, viewer

第一个代码块授予每个角色在该层级上独有的权限。第二个代码块构建层级结构:editor 也是 viewer,而 admin 也是 editor。最后一个代码块将用户分配给角色。结果如下:

UserRolereadcreateupdatedelete
aliceadminyesyesyesyes
bobeditoryesyesyesno
carolvieweryesnonono
dave(none)nononono

4. 添加权限装饰器​

src/permission.decorator.ts
import { SetMetadata } from '@nestjs/common';

export const PERMISSION_KEY = 'permission';

export interface Permission {
resource: string;
action: string;
}

// Declares which permission a route needs, for example @RequirePermission('articles', 'delete').
export const RequirePermission = (resource: string, action: string) =>
SetMetadata(PERMISSION_KEY, { resource, action } as Permission);

5. 添加 Guard​

Guard 从路由的 metadata 中读取权限并询问 Casbin。没有使用该装饰器的路由保持公开。

src/casbin.guard.ts
import { CanActivate, ExecutionContext, ForbiddenException, Inject, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Enforcer } from 'casbin';
import { Request } from 'express';
import { Permission, PERMISSION_KEY } from './permission.decorator';

export const ENFORCER = 'CASBIN_ENFORCER';

@Injectable()
export class CasbinGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
@Inject(ENFORCER) private readonly enforcer: Enforcer,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const permission = this.reflector.getAllAndOverride<Permission>(PERMISSION_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!permission) {
return true; // Routes without @RequirePermission are public.
}

const request = context.switchToHttp().getRequest<Request>();
// Replace this with the user your authentication guard puts on the request, such as request.user.
const user = request.header('X-User') ?? '';

const allowed = await this.enforcer.enforce(user, permission.resource, permission.action);
if (!allowed) {
throw new ForbiddenException();
}
return true;
}
}
备注

X-User header 旨在保持示例简洁。Casbin 仅处理授权。在实际应用中,首先运行一个认证 guard(例如基于 @nestjs/passport 的那个),并设置 request.user;从中读取用户名或 ID。

6. 在控制器中使用​

src/articles.controller.ts
import { Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
import { RequirePermission } from './permission.decorator';

@Controller('articles')
export class ArticlesController {
@Get()
@RequirePermission('articles', 'read')
findAll() {
return { articles: [] };
}

@Post()
@RequirePermission('articles', 'create')
create() {
return { created: true };
}

@Put(':id')
@RequirePermission('articles', 'update')
update(@Param('id') id: string) {
return { updated: id };
}

@Delete(':id')
@RequirePermission('articles', 'delete')
remove(@Param('id') id: string) {
return { deleted: id };
}
}

7. 注册 enforcer 和 guard​

enforcer 由工厂提供者创建一次,并注入到 guard 中。使用 APP_GUARD 注册该 guard 会将其应用于应用程序中的每个路由。

src/app.module.ts
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { newEnforcer } from 'casbin';
import { ArticlesController } from './articles.controller';
import { CasbinGuard, ENFORCER } from './casbin.guard';

@Module({
controllers: [ArticlesController],
providers: [
{
provide: ENFORCER,
useFactory: () => newEnforcer('model.conf', 'policy.csv'),
},
{
provide: APP_GUARD,
useClass: CasbinGuard,
},
],
})
export class AppModule {}

8. 尝试运行​

npm run start
curl -i -X DELETE -H "X-User: alice" http://localhost:3000/articles/1 # 200, admins can delete
curl -i -X DELETE -H "X-User: bob" http://localhost:3000/articles/1 # 403, editors cannot
curl -i -X PUT -H "X-User: bob" http://localhost:3000/articles/1 # 200, editors can update
curl -i -X POST -H "X-User: carol" http://localhost:3000/articles # 403, viewers are read-only
curl -i -H "X-User: carol" http://localhost:3000/articles # 200
curl -i -H "X-User: dave" http://localhost:3000/articles # 403, no role

9. 在运行时管理角色​

在任何需要它的地方注入 enforcer,例如在 admin service 中,使用 @Inject(ENFORCER):

await enforcer.addRoleForUser('dave', 'editor'); // dave becomes an editor
await enforcer.getImplicitRolesForUser('alice'); // [ 'admin', 'editor', 'viewer' ]
await enforcer.getImplicitPermissionsForUser('bob');
// [ [ 'editor', 'articles', 'create' ], [ 'editor', 'articles', 'update' ], [ 'viewer', 'articles', 'read' ] ]

getImplicitPermissionsForUser 适用于“我能做什么”端点,前端用它来显示或隐藏按钮。完整列表见 RBAC API。

下一步​

  • 将策略存储在数据库中。 用 adapter 替换 policy.csv,例如 TypeORM、Prisma、Sequelize 或 MongoDB。通过 API 进行的策略更改会自动保存。
  • 多实例部署。 使用 watcher,以便当其中一个实例更改策略时,所有实例都会重新加载策略。
  • 所有权规则。 “作者只能编辑自己的文章”取决于文章本身,而不仅仅是角色。在 handler 中加载文章,并使用 ABAC 模型进行检查。
  • 多租户应用。 带域名的 RBAC 允许用户在不同租户中拥有不同角色;将租户作为第四个参数添加到 enforce 调用中。
  • 现成的模块。 中间件列表 链接了社区提供的 NestJS 模块,如 nest-authz。

Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.