javascript - NestJS JWT 模块问题

标签 javascript typescript jwt nestjs passport.js

NestJS 中的 JWTModule 存在问题。即使我将 secret 直接传递到配置中而不是通过我的 env 文件,我仍然不断收到此错误。我不知道我错过了什么。

Error: secretOrPrivateKey must have a value

快速概述其工作原理。

  1. 客户端使用 { username: string,password: string } 调用/auth/login
  2. LocalStrategy Guard 将调用 AuthService 的 validateUser 方法,该方法又调用 ldapServices 的authenticateUser 方法并返回用户。
  3. 从那里,我必须从 ldap 获取用户数据,并将其与我们 mongo 数据库中的一些用户数据结合起来。这一切都运行良好。
  4. 通过守卫后,会调用AuthService的登录方法。它应该使用 JwtService(由 NestJS 提供)创建并使用 JWT 签署有效负载。这就是我的问题发生的地方。

以下是文件及其代码:

app.controller.ts

import { Controller, Get, Post, Request, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthService } from './providers/auth/auth.service';
import { LocalAuthGuard } from './providers/auth/local.strategy';

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

  @UseGuards(LocalAuthGuard)
  @Post('/auth/login')
  async login(@Request() req) {
    return this.authService.login(req.user);
  }
}

auth.module.ts

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UserModule } from './../../endpoints/user/user.module';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './local.strategy';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { UserService } from './../../endpoints/user/user.service';
import { LdapService } from './../ldap/ldap-service';
import { jwtConstants } from './constants';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    UserModule,
    PassportModule,
    JwtModule.register({
      secret: '2I*5f5OE9tlGIbg*3Q*C',
      signOptions: { expiresIn: '12h' },
    }),
  ],
  providers: [AuthService, LocalStrategy, LdapService],
  controllers: [AuthController],
  exports: [AuthService],
})
export class AuthModule {}

auth.service.ts

import { Injectable } from '@nestjs/common';
import { LdapService } from '../ldap/ldap-service';
import { UserService } from './../../endpoints/user/user.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private readonly ldapService: LdapService,
    private readonly userService: UserService,
    private readonly jwtService: JwtService
  ) {}

  async validateUser(username: string, pass: string): Promise<any> {
    const authenticated = await this.ldapService.authenticateUser(
      username,
      pass,
    );

    if (authenticated === true) {
      console.log(authenticated, username, pass)
      return await this.userService.getUserById(username);
    }
    return null;
  }

  async login(user: any) {
    const payload = { ...user, sub: user.accountName };
    console.log(process.env.JWT_SECRET, payload);
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}

本地.strategy.ts

import { Strategy } from 'passport-local';
import { AuthGuard, 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();
  }

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

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

我确信我错过了一些小东西。感谢您的帮助。

最佳答案

经过评论讨论后发现AuthService正在通过添加到多个 providers 来重新创建大批。作为JwtService@Optional()要注入(inject)到其中的选项,它在重新创建时没有失败,但它没有将相同的选项传递给 JwtModule.register 。为了纠正这个问题,AuthModule exports: [AuthService]以及任何需要 AuthService 的模块添加imports: [AuthModule]确保只有一个AuthService已创建,并且具有正确的 JwtService带有传递给 JwtModule 的选项

关于javascript - NestJS JWT 模块问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73310341/

相关文章:

javascript - 如何在 jQuery 中的两个不同变量中获取一些第一个字符和其余字符?

javascript - setTimeout() 函数的 TypeScript 装饰器

javascript - 一个模块不能有多个默认导出

json - JWT(json web token) 可以完全取代 Session 吗?

javascript - 身份验证如何跨微服务工作?

c# - 在 ASP.NET Core 2.0 中传递 JSON 对象作为 JWT token 的声明

javascript - Typescript - 导入 Express 不起作用

Javascript onbeforeunload 问题

javascript - 带有 Google 日历日期的 Json 字符串

javascript - TypeScript 与 Node.js ESM 的分歧