Tiếp tục với series, sau Bài 20 TaskFlow API đã biết ai đang gọi, nhưng ai cũng sửa, xoá được project của người khác. Bài này mình sẽ giới thiệu với mọi người về phân quyền trong NestJS.
1. Phân quyền là gì?
Xác thực trả lời câu hỏi "bạn là ai?", còn phân quyền (authorization) trả lời "bạn được làm gì?". Hai kiểu kiểm tra hay gặp:
- Role-based (RBAC): quyền theo vai trò, VD chỉ
adminđược xoá nhật ký. Chỉ cần biết user nên kiểm tra ở guard. - Quyền sở hữu: chỉ chủ project được xem, sửa, xoá nó. Phải biết bản ghi thuộc về ai nên kiểm tra trong service.
Quên kiểm tra quyền sở hữu là lỗi IDOR (Insecure Direct Object Reference): đổi /projects/3 thành /projects/1 là đọc được dữ liệu người khác. Chưa đăng nhập là 401, thiếu role là 403. Với bản ghi của người khác, mình trả 404 như bản ghi không tồn tại: id tăng dần dễ đoán, trả 403 là xác nhận "project 1 có tồn tại" (tài liệu NestJS cũng gợi ý vậy).
2. Thêm role cho user.
Trong prisma/schema.prisma, thêm enum Role { user admin } và cột role Role @default(user) cho model User. Cột có mặc định nên migrate dev chạy được khi bảng đã có dữ liệu. Trong prisma/seed.ts, user [email protected] thêm role: 'admin' ở create và đổi update: {} thành update: { role: 'admin' }:
npx prisma migrate dev --name user_role
npx prisma generate
npx prisma db seed
Thêm role: true vào AUTH_USER_SELECT (src/auth/auth-user.ts) để request.user và GET /auth/me có role.
3. @Roles và RolesGuard.
Bài 12 đã thử @Roles với Reflector.createDecorator(), giờ làm thật với kiểu Role của Prisma Client:
- src/auth/roles.decorator.ts
import { Reflector } from '@nestjs/core';
import type { Role } from '../generated/prisma/client.js';
// @Roles(['admin']): chỉ user có một trong các role này được gọi route
export const Roles = Reflector.createDecorator<Role[]>();
Tạo guard bằng nest g guard auth/roles --no-spec --flat --format rồi sửa thành:
- src/auth/roles.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { AuthRequest } from './auth-user.js';
import { Roles } from './roles.decorator.js';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.getAllAndOverride(Roles, [
context.getHandler(),
context.getClass(),
]);
if (!roles) {
return true; // route không gắn @Roles: mọi user đã đăng nhập
}
const { user } = context.switchToHttp().getRequest<AuthRequest>();
// false -> NestJS trả 403 Forbidden
return user !== undefined && roles.includes(user.role);
}
}
Trong providers của AuthModule, thêm { provide: APP_GUARD, useClass: RolesGuard } ngay sau dòng của JwtAuthGuard: guard toàn cục chạy theo thứ tự đăng ký, guard JWT phải gắn request.user trước. Giờ gắn @Roles(['admin']) dưới @Delete() của ActivitiesController.removeOld() là chỉ admin xoá được nhật ký: không có token vẫn là 401, user thường nhận 403 Forbidden resource.
4. Chỉ chủ project được xem, sửa, xoá.
Cách an toàn nhất là đưa ownerId vào chính câu query thay vì đọc project lên rồi so sánh. Mọi handler lấy user bằng @CurrentUser() user: AuthUser và truyền user.id xuống service:
- src/projects/projects.service.ts (đoạn trích)
async findOne(id: number, userId: number): Promise<ProjectDetail> {
// Project của người khác cũng "không tìm thấy" như project không tồn tại
const project = await this.prisma.project.findUnique({
where: { id, ownerId: userId },
include: projectDetail,
});
if (!project) {
throw new ProjectNotFoundException(id);
}
return project;
}
async update(
id: number,
dto: UpdateProjectDto,
userId: number,
): Promise<Project> {
// Không phải chủ project -> không khớp bản ghi nào -> P2025 -> 404
const project = await this.prisma.project.update({
where: { id, ownerId: userId },
data: dto,
});
// Chỉ lưu các trường client gửi lên
this.log(userId, id, 'updated', dto);
return project;
}
Trong đó:
wherecủafindUnique,update,deletenhận thêm cột không unique nhưownerIdbên cạnhid: kiểm tra và ghi nằm trong một câu lệnh.- Không khớp thì
update/deletebáo lỗi P2025,PrismaExceptionFilter(Bài 16) đổi thành 404.
remove() xoá với where = { id, ownerId: userId }; findAll() thêm ownerId: userId vào where; findLatest() của /projects/latest cũng lọc theo ownerId để không lộ id project của người khác. Với ?moveTasksTo=N, gọi await this.findOne(moveTasksTo, userId) trước transaction để không chuyển được task sang project người khác.
5. Task và activity log.
Task không có ownerId, quyền đi theo project chứa nó: findAll(), findOne(), update(), remove() của TasksService thêm bộ lọc quan hệ project: { ownerId: userId } vào where: Prisma lọc theo cột ownerId của project chứa task (một JOIN ngay trong câu query). projectId client gửi lên cũng phải kiểm tra:
- src/tasks/tasks.service.ts (đoạn trích, thêm import ProjectNotFoundException)
// Project không tồn tại hay của người khác đều trả cùng một lỗi 404
private async checkProject(projectId: number, userId: number) {
const count = await this.prisma.project.count({
where: { id: projectId, ownerId: userId },
});
if (count === 0) {
throw new ProjectNotFoundException(projectId);
}
}
create() gọi await this.checkProject(dto.projectId, userId) đầu tiên, update() gọi khi dto.projectId !== undefined. Với nhật ký hoạt động, schema Activity thêm @Prop({ required: true }) userId: number;, helper log() của hai service nhận thêm userId. Admin xem toàn bộ nhật ký, user thường chỉ xem của mình:
- src/activities/activities.service.ts (đoạn trích, thêm import type AuthUser)
// Admin xem toàn bộ nhật ký, user thường chỉ xem nhật ký của mình
private visibleTo(user: AuthUser): QueryFilter<Activity> {
return user.role === 'admin' ? {} : { userId: user.id };
}
findAll(query, user) lấy this.visibleTo(user) làm bộ lọc ban đầu, findOne(id, user) đổi findById(id) thành findOne({ _id: id, ...this.visibleTo(user) }).
6. Thử chống IDOR với user thứ hai.
Nhật ký cũ không có userId: reset dữ liệu như Bài 20, xoá nhật ký bằng token của tai ($A), rồi đăng ký, đăng nhập An (token $B):
A='Authorization: Bearer <token của tai>'
B='Authorization: Bearer <token của An>'
curl -X DELETE "http://localhost:3000/api/v1/activities?olderThanDays=0" -H "$B"
# {"statusCode":403,"errorCode":"FORBIDDEN","message":"Forbidden resource",...}
curl http://localhost:3000/api/v1/projects -H "$B" -H "Content-Type: application/json" -d '{"name":"Blog"}'
curl http://localhost:3000/api/v1/tasks -H "$A" -H "Content-Type: application/json" \
-d '{"projectId":1,"title":"Sửa giao diện"}'
# {"data":{"id":1,"title":"Sửa giao diện",...,"projectId":1,...}}
curl http://localhost:3000/api/v1/projects -H "$B"
# {"data":[{"id":3,"name":"Blog",...,"ownerId":2,...}],"meta":{...,"total":1,...}}
curl http://localhost:3000/api/v1/projects/1 -H "$B"
# {"statusCode":404,"errorCode":"PROJECT_NOT_FOUND","message":"Không tìm thấy project 1",...}
curl -X DELETE http://localhost:3000/api/v1/tasks/1 -H "$B"
# {"statusCode":404,"errorCode":"NOT_FOUND","message":"Không tìm thấy Task",...}
curl http://localhost:3000/api/v1/tasks -H "$B" -H "Content-Type: application/json" \
-d '{"projectId":1,"title":"Chèn task"}'
# {"statusCode":404,"errorCode":"PROJECT_NOT_FOUND","message":"Không tìm thấy project 1",...}
curl http://localhost:3000/api/v1/activities -H "$B"
# {"data":[{"_id":"...","userId":2,"entity":"project","entityId":3,"action":"created",...}]}
PATCH, DELETE /projects/1 trả 404 Không tìm thấy Project. Project 999 nhận đúng các lỗi này nên An không biết project nào tồn tại. Tai vẫn thấy project 1, task 1 và cả nhật ký của An.
7. Khi luật phân quyền phức tạp hơn.
Khi luật nhiều lên, if rải rác trong service sẽ khó quản lý, nên gom luật về một chỗ:
- CASL (
@casl/ability7.1.3): khai báo luật dạngcan('update', 'Project', { ownerId: user.id }), kiểm tra bằngability.can('update', subject('Project', project));@casl/prismađổi luật thành điều kiệnwherecho Prisma. @nestjs/authorization: package mới trong tài liệu NestJS, viết luật thành class policy. Nó mới ở bản 0.1.4 và đi cùng@nestjs/authenticationnên series chưa dùng.
Dù dùng thư viện nào, nguyên tắc vẫn vậy: role kiểm tra ở guard, quyền sở hữu đưa vào câu query, danh sách lọc trong database.
8. Lời kết.
Như vậy mình đã giới thiệu với mọi người về phân quyền trong NestJS: role với @Roles và RolesGuard, kiểm tra quyền sở hữu cho project, task, activity log và cách chống IDOR. Bài sau mình sẽ giới thiệu về upload file trong NestJS để đính kèm file cho task.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments