【问题标题】:Signing JWT token using pem key converted from Google service account .p12 key使用从 Google 服务帐户 .p12 密钥转换的 pem 密钥签署 JWT 令牌
【发布时间】:2018-09-24 10:47:15
【问题描述】:

在这里,我正在尝试签署一个 JWT 令牌,以便从前端访问 Google 的 API。我创建了一个服务帐户,下载了 p12 密钥并使用以下命令将其转换为 pem 密钥

openssl pkcs12 -in privatekey.p12 -nodes -nocerts --passin pass:notasecret > privateKey.pem

然后我使用 npm 包 jsonwebtoken 使用以下代码返回令牌,该代码适用于我的服务器端代码。

var fs = require('fs');
var jwt = require('jsonwebtoken');
const private_key_file = 'privateKey.pem';
const algorithm = 'RS256';
const projectId = [PROJECT_ID];

function createJwt (projectId, private_key_file, algorithm) {
    // Create a JWT to authenticate this device. The device will be disconnected
    // after the token expires, and will have to reconnect with a new token. The
    // audience field should always be set to the GCP project id.
    const token = {
      'iat': parseInt(Date.now() / 1000),
      'exp': parseInt(Date.now() / 1000) + 1000,
      'aud': projectId
    };
    const privateKey = fs.readFileSync(private_key_file);
    return jwt.sign(token, private_key_file, { algorithm: algorithm });
};

console.log(createJwt(projectId, private_key_file, algorithm));

但是,我一直遇到错误:错误:错误:0906D06C:PEM 例程:PEM_read_bio:没有开始行。我知道这意味着无法正确检测到 pem 文件。我已经进去检查了是否有一些前体行,例如

Bag Attributes
    friendlyName: privateKey
    localKeyID: xx xx xx ...
Key Attributes: <No Attributes>
-----BEGIN PRIVATE KEY-----
....
....
-----END PRIVATE KEY-----

在删除它以仅显示 BEGIN 到 END PRIVATE KEY 之前和之后,我还使用以下命令检查它是否正确加载了密钥文件。

openssl rsa -text -noout -in privateKey.pem

但即便如此,当我使用 node 运行 JWT 签名代码时,错误消息仍然返回 Error: error:0906D06C:PEMroutines:PEM_read_bio:no start line。如果有人可以帮助指出我做错的地方或建议我可以研究的大致方向,那就太好了,谢谢!

【问题讨论】:

  • 啊..这很尴尬..我将错误的变量传递给我的 jwt.sign 函数.. const privateKey = fs.readFileSync(private_key_file); return jwt.sign(token, privateKey, { algorithm: algorithm });

标签: google-cloud-platform jwt service-accounts


【解决方案1】:

在我的代码中犯了一个愚蠢的错误,它应该是以下,现在令牌已成功返回。

   const privateKey = fs.readFileSync(private_key_file);
   return jwt.sign(token, **privateKey**, { algorithm: algorithm });

【讨论】:

  • 感谢您回答自己的问题。这很有帮助。
猜你喜欢
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 2015-10-28
  • 2019-08-27
  • 1970-01-01
  • 2018-11-20
相关资源
最近更新 更多