问题描述
我正在尝试创建一个用于 node.js API 客户端的 JSON Web 密钥集。但是,在记录我的密钥时,它们似乎是空的。
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),4));
解决方法
keystore.generate
是一个异步函数。它返回一个不会立即执行的承诺。您可以使用 .then
或 async/await 来获取承诺的结果。
这是来自库 github 的 example:
keystore.generate("oct",256)。 然后(功能(结果){ // {result} 是一个 jose.JWK.Key 键 = 结果; });
将此应用于您的代码:
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),4));
});
如果您不熟悉 javascript 异步函数,请查看有关该主题的最流行的问答: How do I return the response from an asynchronous call?