Nodejs with typescript TypeError: Passphrase required for encrypted key

Nodejs with typescript TypeError: Passphrase required for encrypted key

我正在尝试在节点 js 中使用 JWT 进行身份验证并遵循本教程 https://www.becomebetterprogrammer.com/jwt-authentication-middleware-nodejs-typescript/ 但是现在我收到这个错误并且不知道如何解决它

import { sign, SignOptions } from 'jsonwebtoken';
import * as fs from 'fs';
import * as path from 'path';

export function generateToken() {
    // information to be encoded in the JWT
    const passphrase = 'shivamyadav';
    const payload = {
        id: 1,  
        email: '',
        role: '',
        iat: new Date().getTime(), // current time,
    };
    // read private key value
    const privateKey = fs.readFileSync(path.join(__dirname, '../../private.pem'), 'utf8');
    // sign with RSA SHA256
    const signInOptions: SignOptions = {
      // RS256 uses a public/private key pair. The API provides the private key
      // to generate the JWT. The client gets a public key to validate the
      // signature
      algorithm: 'RS256',
      expiresIn: '1h',
    };
    
    const token = sign(payload, privateKey, signInOptions);
  }

错误是

node:internal/crypto/sig:131
[1]   const ret = this[kHandle].sign(data, format, type, passphrase, rsaPadding,
[1]                             ^
[1]
[1] TypeError: Passphrase required for encrypted key
[1]     at Sign.sign (node:internal/crypto/sig:131:29)
[1]     at Object.sign (D:\projects\pro14\node_modules\jwa\index.js:152:45)
[1]     at Object.jwsSign [as sign] (D:\projects\pro14\node_modules\jws\lib\sign-stream.js:32:24)
[1]     at module.exports (D:\projects\pro14\node_modules\jsonwebtoken\sign.js:204:16)
[1]     at generateToken (D:\projects\pro14\dist\utils\jwt.utils.js:49:43)
[1]     at Server.<anonymous> (D:\projects\pro14\dist\app.js:25:57)
[1]     at Object.onceWrapper (node:events:509:28)
[1]     at Server.emit (node:events:390:28)
[1]     at emitListeningNT (node:net:1368:10)
[1]     at processTicksAndRejections (node:internal/process/task_queues:82:21) {
[1]   code: 'ERR_MISSING_PASSPHRASE'
[1] }

使用

const privateKey = {
  key: fs.readFileSync(path.join(__dirname, '../../private.pem'), 'utf8'),
  passphrase: <passphrase>
};

其中 <passphrase> 是生成或导出私钥时选择的密码。例如,教程中提到的 openssl genrsa 命令会在生成私钥之前提示您输入密码。