[SOLVED] jwt token with encrypted private key and passphrase

Issue

This Content is from Stack Overflow. Question asked by Afjal

I am tring to generate jwt token with below code

const PRIVATE_KEY_PATH = join(__dirname, ‘./keys/privateob.pem’);

const jws = require(‘jws’);
const ALG = ‘PS256’;enter image description here

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 it 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 Objectenter image description here



Solution

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'});


This Question was asked in StackOverflow by Afjal and Answered by Sain Pradeep 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?