微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法检索dotenv JWT机密“错误:secretOrPrivateKey必须具有值”

如何解决无法检索dotenv JWT机密“错误:secretOrPrivateKey必须具有值”

我正在尝试通过将JWT秘密密钥隐藏到应用程序根目录中本地存储的dotenv文件中来保护我的应用程序,但是文档对我来说还不够清楚,在运行测试时,我一直收到此错误消息:

 console.error
    Error: secretorPrivateKey must have a value
        at Object.module.exports [as sign] (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/node_modules/jsonwebtoken/sign.js:107:20)
        at JwtService.sign (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/node_modules/@nestjs/jwt/dist/jwt.service.js:27:20)
        at AuthService.generatetoken (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/src/auth/auth.service.ts:62:37)
        at AuthService.verifySmsCode (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/src/auth/auth.service.ts:49:19)
        at processticksAndRejections (internal/process/task_queues.js:97:5)
        at Object.<anonymous> (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/src/auth/auth.service.spec.ts:83:30)

      49 |       return this.generatetoken(candidateId)
      50 |     } catch (e) {
    > 51 |       console.error(e)
         |               ^
      52 |       throw new HttpException(
      53 |         ResponseMessage.INVALID_CODE,54 |         HttpStatus.FORBIDDEN

      at AuthService.verifySmsCode (auth/auth.service.ts:51:15)
      at Object.<anonymous> (auth/auth.service.spec.ts:83:30)

这里是.env

JWT_SECRET=secretKey

这里是src/app.module.ts

import { Module } from '@nestjs/common'
import { StatusModule } from './status/status.module'
import { CitiesModule } from './cities/cities.module'
import { PopupModule } from './popup/popup.module'
import { CandidateModule } from './candidate/candidate.module'
import { NotificationModule } from './notification/notification.module'
import { ChatModule } from './chat/chat.module'
import { AuthModule } from './auth/auth.module'
import { SkillInviteModule } from './skill-invite/skill-invite.module'
import { ConfigModule } from '@nestjs/config'

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,}),StatusModule,CitiesModule,PopupModule,CandidateModule,NotificationModule,ChatModule,AuthModule,SkillInviteModule,],})
export class AppModule {}

测试文件

describe('AuthService',() => {
  let service: AuthService
  let authRepository: AuthRepository
  let authGateway: AuthGateway
  let jwtService: JwtService

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        JwtModule.register({
          secret: process.env.JWT_SECRET,providers: [AuthService,AuthRepository,AuthGateway],}).compile()

    service = module.get<AuthService>(AuthService)
    authRepository = module.get<AuthRepository>(AuthRepository)
    authGateway = module.get<AuthGateway>(AuthGateway)
    jwtService = module.get<JwtService>(JwtService)
  })

  it('should be defined',() => {
    expect(service).tobedefined()
  })


[...]

    it('should generate a token that expires within one hour when code is valid',async () => {
      const payload = { candidateId: '1' }

      const verifyResponse = await service.verifySmsCode(phoneNumber,code)
      expect(verifyResponse).toHaveProperty(
        'access_token',jwtService.sign(payload)
      )
      expect(verifyResponse).toHaveProperty('expires_in',1000 * 60 * 60)
    })

最后是要测试的代码


  async verifySmsCode(
    phoneNumber: string,code: string
  ): Promise<VerifyResponSEObject> {
    try {
      const candidateId = await this.authRepository.verifySmsCode(
        phoneNumber,code
      )
      return this.generatetoken(candidateId)
    } catch (e) {
      console.error(e)
      throw new HttpException(
        ResponseMessage.INVALID_CODE,HttpStatus.FORBIDDEN
      )
    }
  }

解决方法

您必须导入dotenv库并对其进行配置,然后才能使用.env中定义的环境变量。将require('dotenv').config()添加到main.ts将解决您的问题。

,

我认为可以通过在单元测试中将for h in 1 .. apex_web_service.g_response_headers.count loop dbms_output.put_line( apex_web_service.g_response_headers(h).name ); dbms_output.put_line( apex_web_service.g_response_headers(h).value ); end loop; 导入ConfigModule来解决此问题:

TestingModule

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?