Hướng Dẫn Tạo Dịch Vụ Xác Thực Trong NestJS Sử Dụng gRPC và API Gateway - Phần 2
Dịch Vụ Xác Thực (grpc-nest-auth-svc)
Cài Đặt Phụ Thuộc
Để xây dựng dịch vụ xác thực trong NestJS với gRPC, chúng ta bắt đầu cài đặt các phụ thuộc cần thiết như sau:
npm install @nestjs/microservices @nestjs/typeorm @nestjs/jwt @nestjs/passport passport passport-jwt typeorm pg class-transformer class-validator bcryptjs
npm install --save-dev @types/node @types/passport-jwt ts-proto
Cấu Trúc Dự Án
Trong phần này, chúng ta sẽ tạo một mô-đun xác thực đơn giản với tên gọi là auth
:
Nest g mo auth && Nest g co auth --no-spec
mkdir src/auth/filter && mkdir src/auth/service && mkdir src/auth/strategy
touch src/auth/filter/http-exception.filter.ts
...
Scripts
Chúng ta cần thêm một số tập lệnh vào package.json
để tự động tạo tệp protobuf cho dự án. Hãy thay thế {{link_github_proto}}
bằng liên kết tới tệp proto của bạn:
"proto:install": "npm install {{link_github_proto}}",
"proto:auth": "protoc --plugin=node_modules/.bin/protoc-gen-ts_proto -I=./node_modules/grpc-nest-proto/proto --ts_proto_out=src/auth/ node_modules/grpc-nest-proto/proto/auth.proto --ts_proto_opt=nestJs=true --ts_proto_opt=fileSuffix=.pb"
Chạy lệnh sau để cài đặt:
npm run proto:install && npm run proto:auth
Bộ Lọc Ngoại Lệ HTTP
Chúng ta cần xử lý các lỗi HTTP nếu có bất kỳ ngoại lệ nào xảy ra trong quá trình xác thực:
typescript
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx: HttpArgumentsHost = host.switchToHttp();
const res: Response = ctx.getResponse<Response>();
const req: Request = ctx.getRequest<Request>();
const status: HttpStatus = exception.getStatus();
...
}
}
DTO Xác Thực
Chúng ta cũng cần định nghĩa các lớp DTO để xử lý dữ liệu xác thực:
typescript
import { IsEmail, IsString, MinLength } from 'class-validator';
export class LoginRequestDto {
@IsEmail() public readonly email: string;
@IsString() public readonly password: string;
}
export class RegisterRequestDto {
@IsEmail() public readonly email: string;
@IsString() @MinLength(8) public readonly password: string;
}
Thực Thể Xác Thực
Mô hình thực thể cho người dùng xác thực:
typescript
import { BaseEntity, Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Auth extends BaseEntity {
@PrimaryGeneratedColumn() public id!: number;
@Column() public email!: string;
@Column() public password!: string;
}
Dịch Vụ JWT
Để quản lý mã thông báo JWT, chúng ta định nghĩa dịch vụ JWT:
typescript
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtService {
public generateToken(auth: Auth): string {
return this.jwt.sign({ id: auth.id, email: auth.email });
}
}
Chiến Lược JWT
Để xác thực những yêu cầu dựa trên JWT:
typescript
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
private validate(token: string): Promise<Auth | never> {
return this.jwtService.validateUser(token);
}
}
Dịch Vụ Xác Thực
Dịch vụ để xử lý các yêu cầu đăng ký, đăng nhập và xác nhận:
typescript
@Injectable()
export class AuthService {
public async register({ email, password }: RegisterRequestDto): Promise<RegisterResponse> {
...
}
}
Bộ Điều Khiển Xác Thực
Để tạo các đường dẫn cho dịch vụ xác thực:
typescript
@Controller()
export class AuthController {
@GrpcMethod(AUTH_SERVICE_NAME, 'Register')
private register(payload: RegisterRequestDto): Promise<RegisterResponse> {
return this.service.register(payload);
}
}
Mô-đun Xác Thực
Tích hợp tất cả các phần trong mô-đun:
typescript
@Module({
providers: [AuthService, JwtService, JwtStrategy],
})
export class AuthModule {}
Mô-đun Chính
Kết nối mô-đun xác thực vào ứng dụng:
typescript
@Module({
imports: [AuthModule],
})
export class AppModule {}
Hàm Khởi Tạo Ứng Dụng
Khởi chạy dịch vụ gRPC:
typescript
async function bootstrap() {
const app: INestMicroservice = await NestFactory.createMicroservice(AppModule, {
transport: Transport.GRPC,
});
await app.listen();
}
bootstrap();
Dịch Vụ Sản Phẩm (grpc-nest-product-svc)
Cài Đặt Phụ Thuộc và Cấu Trúc Dự Án
Tương tự như dịch vụ xác thực, chúng ta sẽ thiết lập một dịch vụ sản phẩm:
bash
npm install @nestjs/microservices @grpc/grpc-js @grpc/proto-loader
Tạo một mô-đun cho sản phẩm:
bash
Nest g mo product && Nest g co product --no-spec
Entity và DTO
Xây dựng các thực thể và DTO cần thiết cho dịch vụ sản phẩm:
typescript
@Entity()
export class Product extends BaseEntity {
...
}
Dịch Vụ và Bộ Điều Khiển
Cũng giống như dịch vụ xác thực, chúng ta sẽ tạo các phương thức cho sản phẩm và xử lý yêu cầu từ khách hàng.
Dịch Vụ Đơn Hàng (grpc-nest-order-svc)
Phần này sẽ mô tả cách tạo dịch vụ đơn hàng, gọi dịch vụ sản phẩm để kiểm tra và giảm lượng hàng tồn kho.
Kết Luận
Trong phần này, chúng ta đã hoàn thiện cách thiết lập dịch vụ xác thực và tích hợp với dịch vụ sản phẩm trong NestJS bằng cách sử dụng gRPC. Bạn có thể sử dụng mô hình này để xây dựng ứng dụng microservices của riêng mình. Chạy tất cả các dịch vụ với lệnh:
npm run start:dev
source: viblo