nestjs 启用全局身份验证
时间: 2023-06-23 21:50:39 浏览: 237
要启用 NestJS 的全局身份验证,你需要执行以下步骤:
1. 安装依赖:
```
npm install --save @nestjs/passport passport passport-local
```
2. 创建一个 `AuthGuard` 类,在其中实现 `CanActivate` 接口,用于检查用户是否已经经过身份验证:
```typescript
import { Injectable } from '@nestjs/common';
import { AuthGuard as NestAuthGuard } from '@nestjs/passport';
@Injectable()
export class AuthGuard extends NestAuthGuard('local') {
canActivate(context) {
return super.canActivate(context);
}
}
```
3. 创建一个 `LocalStrategy` 类,在其中实现 `Strategy` 接口,用于验证用户的身份:
```typescript
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
```
4. 在 `app.module.ts` 中配置全局身份验证:
```typescript
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'local' }),
],
providers: [AuthService, LocalStrategy],
exports: [PassportModule, AuthService],
})
export class AuthModule {}
```
5. 在需要进行身份验证的路由上使用 `AuthGuard` 类:
```typescript
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';
@Controller()
export class AppController {
@Get('protected')
@UseGuards(AuthGuard)
protectedRoute() {
return 'This route is protected';
}
}
```
以上就是启用 NestJS 的全局身份验证的步骤。
阅读全文