Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google cloud platform 使用从Google服务帐户转换的pem密钥签名JWT令牌。p12密钥_Google Cloud Platform_Jwt_Service Accounts - Fatal编程技术网

Google cloud platform 使用从Google服务帐户转换的pem密钥签名JWT令牌。p12密钥

Google cloud platform 使用从Google服务帐户转换的pem密钥签名JWT令牌。p12密钥,google-cloud-platform,jwt,service-accounts,Google Cloud Platform,Jwt,Service Accounts,在这里,我试图签署一个JWT令牌,用于从前端访问google的API。我创建了一个服务帐户,下载了p12密钥,并使用以下命令将其转换为pem密钥 openssl pkcs12 -in privatekey.p12 -nodes -nocerts --passin pass:notasecret > privateKey.pem 然后,我使用npm包jsonwebtoken返回一个令牌,使用以下代码,该代码适用于我的服务器端代码 var fs = require('fs'); var jw

在这里,我试图签署一个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-----

但即便如此,当我使用node运行JWT签名代码时,错误消息仍然返回错误:error:0906D06C:PEM routines:PEM_read_bio:no start line。如果有人能帮我指出哪里做错了,或者建议一个大致的方向,那就太好了,谢谢

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

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

啊。。这太尴尬了。。我将错误的变量传递到jwt.sign函数中。。const privateKey=fs.readFileSync(private_key_file);返回jwt.sign(token,privateKey,{algorithm:algorithm});谢谢你回答自己的问题。这很有帮助。
   const privateKey = fs.readFileSync(private_key_file);
   return jwt.sign(token, **privateKey**, { algorithm: algorithm });