1

我正在使用 NestJS 框架。我有一个LocalStrategy来验证用户。现在我想要另一个名为MylocalStrategy. 为此,我添加了两个文件:mylocal.strategy.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)我得到错误:'Unknown authentication strategy "mylocal"'

可能是什么问题呢?

4

1 回答 1

0

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

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;
  }
}

一次性密码策略

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;
  }
}
于 2022-02-06T05:34:35.310 回答