[SOLVED] How to Generate jwt token with encrypted private key and passphrase – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Afjal khan

I am tring to generate jwt token with below code

const { join } = require("path");
const { readFileSync } = require("fs");
const PRIVATE_KEY_PATH = join(__dirname, "./keys/private.pem");

const jws = require("jws");
const ALG = "PS256";

const privateKey = {
    key: readFileSync(PRIVATE_KEY_PATH, "utf8").toString(),
    passphrase: "Passphrasehere",
};
const payload = {
    foo: "bar",
};

const token = jws.sign({
    header: { alg: ALG },
    payload,
    privateKey,
});

But it showing error –

TypeError [ERR_INVALID_ARG_TYPE]: The “key.key” property must be of type string or an instance of Buffer, TypedArray, DataView, or KeyObject. Received an instance of Object at prepareAsymmetricKey (internal/crypto/keys.js:288:13)



Solution

Could be one of the following:

According to ECMAScript Language Specification:

15.2.4.2 Object.prototype.toString ( ) When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".


This Question was asked in StackOverflow by Afjal khan and Answered by user3709812 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?