多个本地策略在PassportStrategy中不起作用 [英] Multiple local strategy not working in PassportStrategy

查看:78
本文介绍了多个本地策略在PassportStrategy中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NestJS框架。我有一个LocalStrategy来验证用户。现在,我需要名为MylocalStrategy的另一个LocalStrategy。为此,我添加了两个文件:mylocal.Strategy y.ts和MyLocal-auth.Guard.ts

以下是我的mylocal-auth.guard.ts内容:

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class MylocalAuthGuard extends AuthGuard('mylocal') {}

但是当我使用@UseGuards(MylocalAuthGuard)时,我收到错误:‘未知身份验证策略&Quot;MyLocal&Quot;’

可能是什么问题?

推荐答案

您必须命名策略并在提供商中注册。对我来说,它适用于以下设置

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('UsernamePasswordStrategy') {}

@Injectable()
export class OTPAuthGuard extends AuthGuard('OTPStrategy') {}

用户名和密码策略

import { Strategy } from 'passport-local';

@Injectable()
export class LocalStrategy extends PassportStrategy(
  Strategy,
  'UsernamePasswordStrategy',
) {
  constructor(
    @Inject(IAuthService)
    private readonly authService: IAuthService,
  ) {
    super({
      usernameField: 'user_name',
      passwordField: 'password',
    });
  }

  async validate(user_name: string, password: string): Promise<any> {
    const loginDto = new LoginDto();
    loginDto.userName = user_name;
    loginDto.password = password;
    const user: UserDto = await this.authService.validateUser(loginDto);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

OTP策略

import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { IAuthService } from '../services';
import { OtpLoginDto } from '../dto';
import { UserDto } from 'src/modules/user/dto';
import { plainToClass } from 'class-transformer';

@Injectable()
export class OTPStrategy extends PassportStrategy(Strategy, 'OTPStrategy') {
  constructor(
    @Inject(IAuthService)
    private readonly authService: IAuthService,
  ) {
    super({
      usernameField: 'phone',
      passwordField: 'otp',
    });
  }

  async validate(phone: string, otp: string): Promise<any> {
    const loginDto = plainToClass(OtpLoginDto, {
      phone: phone,
      otp: otp,
    });
    const user: UserDto = await this.authService.verifyOtp(loginDto);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

这篇关于多个本地策略在PassportStrategy中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆