NestJs:处理身份验证和授权
使用 Nest.js 开发项目时,处理身份验证和授权是常见的需求,可以采用以下架构和实现方式。
架构
-
用户认证模块 (Auth Module):
- 服务 (Service): 处理用户登录逻辑,生成 JWT(JSON Web Token),以及验证 token。
- 控制器 (Controller): 提供登录接口,处理来自客户端的请求。
- 中间件/守卫 (Guards): 在需要保护的路由中,验证请求头中的 token,决定是否放行。
-
JWT 模块:
- 利用 Nest.js 提供的 JWT 模块来简化 token 的生成与验证。
-
数据库模块:
- 用于存储和查询用户信息,可能使用 TypeORM 或 Mongoose 等库来操作数据库。
实现步骤
1. 安装所需的依赖
在项目中安装以下依赖:
npm install @nestjs/jwt @nestjs/passport passport passport-jwt bcrypt
2. 创建 Auth Module
生成 Auth 模块:
nest g module auth
nest g controller auth
nest g service auth
3. 实现用户登录逻辑
在 auth.service.ts
中实现用户登录和 token 生成逻辑:
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service'; // 假设你有一个用户服务
import { User } from '../user/user.entity'; // 假设你有一个用户实体
import * as bcrypt from 'bcrypt';@Injectable()
export class AuthService {constructor(private userService: UserService,private jwtService: JwtService,) {}async login(username: string, password: string): Promise<string> {const user: User = await this.userService.findByUsername(username);if (user && await bcrypt.compare(password, user.password)) {const payload = { username: user.username, sub: user.id };return this.jwtService.sign(payload);}throw new Error('Invalid credentials');}
}
4. 创建登录接口
在 auth.controller.ts
中添加登录接口:
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';@Controller('auth')
export class AuthController {constructor(private authService: AuthService) {}@Post('login')async login(@Body() loginDto: { username: string; password: string }) {return this.authService.login(loginDto.username, loginDto.password);}
}
5. 设置 JWT 模块
在 auth.module.ts
中配置 JWT 模块:
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserService } from '../user/user.service'; // 引入用户服务@Module({imports: [JwtModule.register({secret: 'your_secret_key', // 应该放在环境变量中signOptions: { expiresIn: '60s' }, // token 过期时间}),],controllers: [AuthController],providers: [AuthService, UserService],
})
export class AuthModule {}
6. 创建 JWT 校验守卫
创建一个守卫来验证 token,在 auth.guard.ts
中实现:
import { Injectable, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {handleRequest(err, user) {if (err || !user) {throw new UnauthorizedException();}return user;}
}
7. 设置 JWT 策略
在 auth.strategy.ts
中定义 JWT 策略:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { UserService } from '../user/user.service'; // 引入用户服务
import { JwtPayload } from './jwt.payload'; // 定义 payload 接口@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {constructor(private userService: UserService) {super({jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),ignoreExpiration: false,secretOrKey: 'your_secret_key', // 应该放在环境变量中});}async validate(payload: JwtPayload) {return this.userService.findById(payload.sub); // 根据 payload.sub 查找用户}
}
8. 保护路由
在需要保护的控制器中使用守卫:
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from './auth.guard';@Controller('protected')
export class ProtectedController {@UseGuards(JwtAuthGuard)@Get()getProtectedResource() {return 'This is a protected resource';}
}
总结
通过以上步骤,可以实现一个简单的用户登录和 JWT 身份验证系统。用户登录时会生成 token,而在需要保护的接口中,通过中间件校验 token 的有效性,以决定是否放行请求。建议把 secret key 存放在环境变量中,以增强安全性。