安装相关依赖
虽然仅使用@nestjs/jwt就能实现身份验证的功能,但是使用passport能在更高层次上提供更多便利。Passport 拥有丰富的 strategies 生态系统,实现了各种身份验证机制。虽然概念简单,但你可以选择的 Passport 策略集非常丰富且种类繁多。Passport 将这些不同的步骤抽象为一个标准模式,@nestjs/passport
模块将这个模式封装并标准化为熟悉的 Nest 结构。
安装相关依赖:
npm i passport passport-jwt @nestjs/passport @nestjs/jwt
npm i --save-dev @types/passport-jwt
创建身份验证模块
我们将从生成一个 AuthModule
开始,然后在其中生成一个 AuthService
和一个 AuthController
。我们将使用 AuthService
来实现身份验证逻辑,使用 AuthController
来公开身份验证端点。
$ nest g module auth
$ nest g controller auth
$ nest g service auth
local身份验证
首先我们需要安装所需的包。Passport 提供了一种称为 passport-local 的策略,它实现了用户名/密码身份验证机制,适合我们对这部分用例的需求。安装本地验证策略依赖:
npm install --save passport-local
npm install --save-dev @types/passport-local
实现本地验证策略:
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) {
//指定username为account字段
super({ usernameField: 'account' });
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
在AuthService
中实现验证账户和密码的功能:
async validateUser(account: string, password: string): Promise<UserEntity>