jwt token with encrypted private key and passphrase

Viewed 60

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)

1 Answers

It looks like a problem in your file reading. Please check Example here

const fs = require('fs'); // missing in your code
// read file content in data
const data=fs.readFileSync(PRIVATE_KEY_PATH,{ encoding: 'utf8' });
  
const privateKey = {
        // pass data here
  key:data, 
  passphrase: 'Passphrasehere'
} 

or try this

var cert = fs.readFileSync('PRIVATE_KEY_PATH'));
jwt.sign({ foo: 'bar' }, { key: cert, passphrase: 'Passphrasehere' }, { algorithm: 'PS256'});
Related