Nestjs教程使用Passport进行身份验证

在使用NestJS进行身份验证时遇到了一些问题:

  1. 按照Passport官方文档配置后,为什么策略中的validate方法始终没有被调用?
  2. 如何正确地在NestJS中集成Passport的本地策略和JWT策略,有没有完整的示例代码可以参考?
  3. 自定义Passport策略时,如何处理异步验证逻辑(比如需要查询数据库验证用户)?
  4. 返回401错误时,怎样统一格式错误响应?目前直接抛出UnauthorizedException会暴露内部错误细节。
  5. 多个路由需要不同验证策略(如/admin用JWT,/login用本地策略),如何在同一个项目中混合配置?
3 回复

在NestJS中使用Passport进行身份验证,首先需要安装相关依赖:

npm install @nestjs/passport passport passport-local bcryptjs --save

然后配置Passport模块:

  1. 创建一个AuthModule,并引入PassportModule。
  2. 定义User实体和相应的UserService。
  3. 配置LocalStrategy,处理本地用户名/密码登录逻辑。

示例代码:

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';
import { UsersModule } from '../users/users.module';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';

@Module({
  imports: [
    UsersModule,
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: 'your-secret-key',
    }),
  ],
  providers: [AuthService, LocalStrategy],
})
export class AuthModule {}

最后,在Controller中使用@UseGuards(AuthGuard(‘local’))来保护路由。确保加密用户密码并妥善管理JWT令牌。


要使用Passport在NestJS中实现身份验证,首先安装必要的依赖:

npm install @nestjs/passport passport passport-local bcryptjs

然后配置AppModule导入PassportModule

import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { PassportModule } from '@nestjs/passport';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'local' }),
  ],
  providers: [],
})
export class AppModule {}

创建一个本地策略LocalStrategy

import { Injectable, UnauthorizedException } 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;
  }
}

最后,在控制器中使用@UseGuards(AuthGuard('local'))来保护路由:

import { Controller, Post, Body, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('login')
  @UseGuards(AuthGuard('local'))
  async login(@Body() body: { username: string; password: string }) {
    return this.authService.login(body.username);
  }
}

记得在AuthService中实现validateUser逻辑。

在NestJS中使用Passport进行身份验证的简明教程:

  1. 安装必要依赖:
npm install @nestjs/passport passport passport-local
npm install @types/passport-local -D
  1. 创建本地策略(LocalStrategy):
// local.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super();
  }

  async validate(username: string, password: string) {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
  1. 创建Auth模块:
// auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './local.strategy';
import { AuthService } from './auth.service';

@Module({
  imports: [PassportModule],
  providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
  1. 在控制器中使用:
// auth.controller.ts
import { Controller, Post, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
  [@UseGuards](/user/UseGuards)(AuthGuard('local'))
  @Post('login')
  async login(@Request() req) {
    return req.user;
  }
}
  1. 基本配置完成后,你可以:
  • 扩展其他策略(如JWT、OAuth等)
  • 使用自定义守卫
  • 添加会话支持

关键点:

  • PassportStrategy是NestJS对Passport的封装
  • validate方法用于验证用户凭证
  • @UseGuards(AuthGuard(‘strategy-name’))保护路由

JWT扩展:

npm install @nestjs/jwt passport-jwt
npm install @types/passport-jwt -D

这是基本实现,实际项目中还需添加用户服务、加密等模块。

回到顶部