1

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.

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm probably missing something obvious, but where does my public key go, in JWT.io it accepts both public and private? Also, headers? I think that is in options, is that covered with the algorithm choice? My header is just { "alg": "RS256", "typ": "JWT" }
@edencorbin The public key is only needed to verify the signature, therefore you use it with jwt.verify(). For signing, you only need the private key, as shown in the answer.
This did indeed work, I was confused why you enter the public one in JWT.io.
@edencorbin you pass in the public key in JWT.io to verify that the JWT you pasted in the tool was indeed signed with the private key belonging to the public key
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.