0

我正在尝试创建一个 JSON Web 密钥集以用于 node.js API 客户端。但是,在记录我的密钥时,它们似乎是空的。

const {JWKS} = require("jose");
const keyAlg = "RSA";
const keySize = 2048;
const keyUse = "sig";
const alg = "RS256";
const keystore = new JWKS.KeyStore();
keystore.generate(keyAlg, keySize, {
  alg,
  use: keyUse,
});

console.log("Public keys");
console.log("This can be used as the jwks in your API client configuration in the portal");
console.log(JSON.stringify(keystore.toJWKS(), null, 4));
console.log("Private keys");
console.log("This can be used as the keys value when configuring the api client");
console.log(JSON.stringify(keystore.toJWKS(true), null, 4));
4

1 回答 1

1

keystore.generate是一个异步函数。它返回一个不会立即执行的承诺。您可以使用.then或 async/await 来获取承诺的结果。

这是来自库 github的示例:

keystore.generate("oct", 256)。then(function(result) { // {result} 是 jose.JWK.Key key = result; });

将此应用于您的代码:

const {JWKS} = require("jose");
const keyAlg = "RSA";
const keySize = 2048;
const keyUse = "sig";
const alg = "RS256";
const keystore = new JWKS.KeyStore();
keystore.generate(keyAlg, keySize, {
  alg,
  use: keyUse,
}).then(function(result) {
  
  console.log(result);
  console.log("Public keys");
  console.log("This can be used as the jwks in your API client configuration in the portal");
  console.log(JSON.stringify(keystore.toJWKS(), null, 4));
  console.log("Private keys");
  console.log("This can be used as the keys value when configuring the api client");
  console.log(JSON.stringify(keystore.toJWKS(true), null, 4));
});

如果您不熟悉 javascript 异步函数,请查看有关该主题的最流行的问题和答案: 如何从异步调用返回响应?

于 2021-02-08T13:41:52.713 回答