NestJs Passport jwt 未知策略

NestJs Passport jwt unknown strategy

我正在尝试在我的嵌套应用程序中实施 JWT 身份验证策略。
我收到以下错误

Unknown authentication strategy "jwt"

这是我的代码:
jwt.strategy.ts

import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy } from "passport-local";
import { ExtractJwt } from "passport-jwt";
import { jwtConstants } from "./constants";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    })
  }

  async validate(payload: any) {
    console.log(payload);
    return { userId: payload.sub, username: payload.username };
  }
}

我的身份验证模块:
authentication.module.ts

import { Module } from '@nestjs/common';
import { AuthenticationService } from './authentication.service';
import { UsersModule } from 'src/users/users.module';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './local.strategy';
import { JwtModule } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { JwtStrategy } from './jwt.strategy';

@Module({
  providers: [
    AuthenticationService,
    LocalStrategy,
    JwtStrategy
  ],
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: "1d" },
    })
  ],
  exports: [AuthenticationService]
})
export class AuthenticationModule {}

我正在尝试在以下控制器中使用它:
users.controller.ts

import { Controller, Post, Body, Put, Param, Get, UseGuards } from '@nestjs/common';
import { User } from './user.entity';
import { UsersService } from './users.service';
import { JwtAuthGuard } from 'src/authentication/jwt-auth.guard';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @UseGuards(JwtAuthGuard)
  @Get()
  async getAll(){
    return this.usersService.findAll();
  }
}

用户模块如下所示:
users.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UsersService],
  controllers: [UsersController],
  exports: [UsersService]
})
export class UsersModule {}

JwtAuthGuard只是从 AuthGuard('jwt') 延伸而来的 class 我已遵循官方文档中的 nestjs 身份验证指南,但无法在我的 UsersModule

中获取它 运行

在您的用户模块中导入您的身份验证模块,然后您的用户服务将检测到它。

user.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
// import authentication module here

@Module({
  imports: [
    AuthenticationModule, // add this here
    TypeOrmModule.forFeature([User])
  ],
  providers: [UsersService],
  controllers: [UsersController],
  exports: [UsersService]
})
export class UsersModule {}

authentication.module.ts

import { Module } from '@nestjs/common';
import { AuthenticationService } from './authentication.service';
import { UsersModule } from 'src/users/users.module';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './local.strategy';
import { JwtModule } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { JwtStrategy } from './jwt.strategy';

@Module({
  providers: [
    AuthenticationService,
    LocalStrategy,
    JwtStrategy
  ],
  imports: [
    // UsersModule, # exclude this, your authentication module is not using it
    PassportModule,
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: "1d" },
    })
  ],
  exports: [
    JwtModule,
    PassportModule,
    AuthenticationService,

  ]
})
export class AuthenticationModule {}

我还注意到您在 AuthenticationModule 中导入了 UserModule,但是从您的代码中您并没有在任何地方使用它。所以请删除它以避免循环依赖。

问题是 autoimport 从错误的包中导入了 Strategy

import {Strategy} from "@nest/passport-local";

而不是

import { Strategy } from "passport-jwt";

对我来说,我缺少将 JwtStrategy 导入 auth.module.ts providers

@Module({
  controllers: [AuthController],
  imports: [
    PassportModule,
    JwtModule.register({
      secret: 'nomnom',
      signOptions: { expiresIn: '1d' },
    }),
  ],
  exports: [AuthService],
  providers: [AuthService, AccountService, LocalStrategy, JwtStrategy], // Here, make sure you have imported LocalStrategy and JwtStrategy.
})
export class AuthModule {}