生成 JSON Web 密钥集 (JWKS)

问题描述

我正在尝试创建一个用于 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?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...