Nest.js权限管理系统开发(八)jwt登录

安装相关依赖

虽然仅使用@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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值