Node.js 谷歌Api服务帐户;错误";:&引用;无效的“授权”&引用;错误描述:&引用;JWT签名无效。”;

Node.js 谷歌Api服务帐户;错误";:&引用;无效的“授权”&引用;错误描述:&引用;JWT签名无效。”;,node.js,google-api,jwt,Node.js,Google Api,Jwt,我对GoogleAPI相当陌生,但我已经花了6个小时来处理这个错误。所以我想用服务帐户访问我的谷歌硬盘文件。但我总是犯这样的错误: {“错误”:“无效授权”,“错误描述”:“无效JWT签名”。} 这是我在NodeJs中创建和发送JWT的方法: const privateKeyFile = require("./user.json"); const base64url = require("base64url"); const jsonwebtoken = require("jsonwebtoke

我对GoogleAPI相当陌生,但我已经花了6个小时来处理这个错误。所以我想用服务帐户访问我的谷歌硬盘文件。但我总是犯这样的错误:

{“错误”:“无效授权”,“错误描述”:“无效JWT签名”。}

这是我在NodeJs中创建和发送JWT的方法:

const privateKeyFile = require("./user.json");
const base64url = require("base64url");
const jsonwebtoken = require("jsonwebtoken");
const querystring = require("querystring");
const request = require("request");

// HEADER
let header = { alg: "RS256", typ: "JWT" };
let encodedH = base64url(JSON.stringify(header));

// CLAIM SET
let exp = parseInt(Date.now() / 1000) + 60 * 20;
// issue time
let iat = parseInt(Date.now() / 1000);
let claimset = {
  iss: "*********@*******.iam.gserviceaccount.com",
  scope: "https://www.googleapis.com/auth/drive",
  aud: "https://oauth2.googleapis.com/token",
  exp: exp,
  iat: iat,
};
let encodedCs = base64url(JSON.stringify(claimset));


// create signiture
let signitureBase = encodedH + "." + encodedCs;
jsonwebtoken.sign(
  signitureBase,
  privateKeyFile.private_key,
  {
    algorithm: "RS256",
    header: header,
  },
  function (err, signature) {
    request.post(
      "https://oauth2.googleapis.com/token",
      {
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: querystring.encode({
          grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
          assertion: signitureBase + "." + base64url(signature),
        }),
      },
      function (error, response) {
        console.log(error);
        console.log(response);
      }
    );
  }
);

提前谢谢

我相信你的目标如下

  • 您希望使用Node.js从Google服务帐户检索访问令牌
对于这个问题,这个答案如何

模式1: 在此模式中,使用了
加密
请求

示例脚本: 结果: 运行脚本时,将检索以下结果

{
  "access_token": "###",
  "expires_in": ####,
  "token_type": "Bearer"
}
{
  "Authorization": "Bearer ###"
}
模式2: 在该模式中,使用了

示例脚本: 结果: 运行脚本时,将检索以下结果

{
  "access_token": "###",
  "expires_in": ####,
  "token_type": "Bearer"
}
{
  "Authorization": "Bearer ###"
}
参考:

太完美了!非常感谢!:)@谢谢你的答复。我很高兴你的问题解决了。