Home > front end >  Generate a JWT in Node using inputs like jwt IO
Generate a JWT in Node using inputs like jwt IO

Time:01-05

I have a header, payload, and a public/private key. I can plug these all into JWT.io and it works as expected, but I'm struggling how to use these same variables with a node library like jsonwebtoken or other similar options. They seem to take a secret and sign a payload as far as I can see, which doesn't seem to line up with my inputs. I need to dynamically generate this token request so I must have the function in Node.

Thanks for any tips.

CodePudding user response:

Have a look at the jsonwebtoken NPM package, which offers amongst other methods, a sign method:

var jwt = require('jsonwebtoken');

var privateKey = fs.readFileSync('private.key');
var payload = { foo: 'bar' };
var token = jwt.sign(payload, privateKey, { algorithm: 'RS256' });

As @jps has pointed out, you need the private key to sign and the public key to verify.

The header will be automatically generated and will include both properties (alg and typ) you have mentioned in your comment. You can add additional properties by passing them in the options.header parameter.

CodePudding user response:

I'm struggling how to use these same variables with a node library

import * as jose from 'jose';

const privateKey = await jose.importPKCS8(privateKeyPEM); // private key just like on jwt.io

const jwt = await new jose.SignJWT(payload) // payload just like on jwt.io
  .setProtectedHeader(header) // header just like on jwt.io
  .sign(privateKey);

Of course there's more to be discovered if you need it.

  • Related