【问题标题】:NestJS Unknown authentication strategy "local"NestJS 未知身份验证策略“本地”
【发布时间】:2022-07-19 16:15:09
【问题描述】:

我在 NestJs 中有这段代码,下面有以下文件,但现在它显示“未知身份验证策略“本地””, 我已经在寻找解决方案,它们都指向一个导入错误,但是我将 localstrategy 导入到 auth.module 和 app.module 中(我已经测试过将它从 app.module 中取出,但它并没有改变任何东西.)

app.module.ts

    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { ThrottlerModule } from '@nestjs/throttler';
    import { MongooseModule } from '@nestjs/mongoose';
    import { AuthModule } from './auth/auth.module';
    import { UsersModule } from './users/users.module';
    import { LocalStrategy } from './auth/local.strategy';

    @Module({
      imports: [
        MongooseModule.forRoot(
          'mongodb+srv://user:password@db.db.mongodb.net/db?retryWrites=true&w=majority',
        ),
        ThrottlerModule.forRoot({
          ttl: 60,
          limit: 10,
        }),
        AuthModule,
        UsersModule,
      ],
      controllers: [AppController],
      providers: [AppService, LocalStrategy],
    })
    export class AppModule {}

auth.module.ts

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

  @Module({
    imports: [
      UsersModule,
      PassportModule,
      JwtModule.register({
        secret: process.env.JWTSECRET,
        signOptions: { expiresIn: '60s' },
      }),
    ],
    providers: [AuthService, LocalStrategy, JwtStrategy],
    exports: [AuthService],
  })
  export class AuthModule {}

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({ usernameField: 'email' });
    }

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

app.controller.ts

    import {
  Controller,
  Request,
  Post,
  UseGuards,
  Res,
  Get,
  Body,
} from '@nestjs/common';
import { AuthService } from './auth/auth.service';
import { MakeAuthDto } from './auth/dto/make-auth.dto';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { LocalAuthGuard } from './auth/local-auth.guard';
import { Roles } from './utils/decorators/roles.decorator';
import { Role } from './utils/enums/role.enum';
import { RolesGuard } from './utils/guards/roles.guard';

@Controller()
export class AppController {
  constructor(private authService: AuthService) {}

  @UseGuards(LocalAuthGuard)
  @Post('auth/login')
  async login(
    @Body() _: MakeAuthDto,
    @Request() req,
    @Res({ passthrough: true }) res,
  ) {
    console.log(req.user);
    const access_token = await this.authService.login(req.user);
    res.cookie('jwt', access_token);
    return req.user;
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(Role.Admin)
  @Get('tests')
  getProfile(@Request() req) {
    return req.user;
  }
}

local-auth.guard.ts

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

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

auth.service.ts

    import { Injectable } from '@nestjs/common';
import { UsersService } from 'src/users/users.service';
import { JwtService } from '@nestjs/jwt';
import { UserDocument } from 'src/users/entities/user.entity';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(email: string, pass: string): Promise<UserDocument | any> {
    const user = await this.usersService.findOne(email);
    if (user && (await user.compareHash(pass))) {
      const { password, ...result } = user.toObject();
      await this.usersService.updateLastLogin(user._id);
      return result;
    }
    return null;
  }

  async login(user: UserDocument): Promise<string> {
    const payload = { email: user.email, sub: user._id, roles: user.roles };
    return this.jwtService.sign(payload);
  }
}

jwt-auth.guard.ts

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

    @Injectable()
    export class JwtAuthGuard extends AuthGuard('jwt') {}

jwt.strategy.ts

    import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import 'dotenv/config';

const cookieExtractor = function (req) {
  let token = null;
  if (req && req.cookies) {
    token = req.cookies['jwt'];
  }
  return token;
};

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([cookieExtractor]),
      ignoreExpiration: false,
      secretOrKey: process.env.JWTSECRET,
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, email: payload.email, roles: payload.roles };
  }
}

stackoverflow 上没有类似的问题解决了我的问题,有人知道它是什么吗?

【问题讨论】:

  • 不确定这是否是技术上的问题,但使用最新版本的护照0.5.0,您必须致电passport.initialize(),例如app.use(passport.initialize()),以获得基于快递的应用程序。我想知道这是否可能是原因。
  • @AlexanderStaroselsky 我需要把这个放在哪里?
  • 好吧,在标准的快递应用程序中,它在主文件app.js 中就是这样的。您可以尝试在main.ts(初始化文件)或类似文件中简单地执行use 语句。 import * as passport from 'passport'; //.. app.use(passport.initialize());
  • 您的UsersService 请求是否有范围?
  • 就我而言,我的 AppModule 没有 LocalStrategy 作为提供者,只有 AuthModule。由于您的 AppModule 不导入 Passport,这是否会导致问题?另外,您还没有分享您对 AppService 的定义,所以我无法判断它是否使用该策略。

标签: node.js typescript passport.js nestjs passport-local


【解决方案1】:

我通过将LocalAuthGuard 替换为LocalStrategy 解决了我的问题

@UseGuards(LocalAuthGuard)
  @Post('auth/login')
  async login
  ....

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2018-06-08
    • 2017-05-25
    • 2016-02-28
    • 2022-01-11
    • 2014-02-22
    • 1970-01-01
    • 2021-08-22
    • 2019-04-30
    相关资源
    最近更新 更多