生成一个JWT令牌,使用Node并提供类似jwt IO的输入。

huangapple go评论59阅读模式
英文:

Generate a JWT in Node using inputs like jwt IO

问题

我有一个头部、有效负载以及一个公钥/私钥。我可以将所有这些信息都输入到JWT.io中,它能按预期工作,但我不知道如何在Node.js中使用这些相同的变量,例如使用jsonwebtoken或其他类似的选项。据我所见,它们似乎需要一个密钥来对有效负载进行签名,这似乎与我的输入不符。我需要动态生成这个令牌请求,所以我必须在Node.js中编写相应的函数。

感谢任何提示。

英文:

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.

答案1

得分: 1

请查看jsonwebtoken NPM包,它提供了sign等方法:

var jwt = require('jsonwebtoken');

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

正如 @jps 指出的,您需要私钥来签名和公钥来验证。

标头将自动生成并包括您在评论中提到的两个属性(algtyp)。您可以通过将它们传递到options.header参数中来添加其他属性。

英文:

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.

答案2

得分: 1

我在如何使用同样的变量与一个Node库中遇到了困难

```js
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);

当然,如果需要的话,还有更多内容可以发现


<details>
<summary>英文:</summary>

&gt; I&#39;m struggling how to use these same variables with a node library

```js
import * as jose from &#39;jose&#39;;

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.

huangapple
  • 本文由 发表于 2023年1月4日 19:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75004865.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定