【问题标题】:JWT Authentication in Google Cloud FunctionsGoogle Cloud Functions 中的 JWT 身份验证
【发布时间】:2018-07-23 17:19:06
【问题描述】:

在使用 Google Cloud Function 中的模块“googleapis”调用时,我无法解决来自 Google Dataflow API 的 403 响应的原因。

该代码在我的 PC 上运行时使用与在 Cloud Functions 上运行的相同代码。 正在从存储在 Google 存储桶上的对象中检索 JWT .json 文件。

代码如下:

...
return getToken(). //Retrieves the JWT Client from Google Storage
      then(function (jwtToken) {
        console.log("Token: ", JSON.stringify(jwtToken));
        return dataFlowList({
          projectId: adc.projectId,
          auth: jwtToken,
          filter: "TERMINATED"
        }).then(list => filterDataflowJobList(list))
...

这里是getToken 函数:

...
let storage: CloudStorage.Storage = CloudStorage({
  projectId: adc.projectId
});
var bucket: CloudStorage.Bucket = storage.bucket(bucketName);

var bucketGetFiles = PromiseLab.denodeify(bucket.getFiles);

var stream = bucket.file(jwtJsonFileName).createReadStream();
return toString(stream)
  .then(function (msg) {
    var jsonJwt = JSON.parse(msg);
    var jwtClient = new google.auth.JWT(
      jsonJwt.client_email,
      null,
      jsonJwt.private_key,
      ['https://www.googleapis.com/auth/cloud-platform'], // an array of auth scopes
      null
    );
    return jwtClient;
  }).catch(function (error) {
    console.log("Error while trying to retrieve JWT json");
    throw error;
  })
}
...

我位于欧盟,而 Cloud Functions 与美国有关,可能是这种情况吗? 数据流作业也在美国运行

【问题讨论】:

    标签: google-app-engine google-cloud-dataflow google-api-nodejs-client


    【解决方案1】:

    在 Google Function 上运行时,我使用的身份验证检索方法不是检索 projectId,因此是未经授权的。

    async function getADC() {
      // Acquire a client and the projectId based on the environment. This method looks
      // for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS environment variables.
      const res = await auth.getApplicationDefault();
      let client = res.credential;
    
      // The createScopedRequired method returns true when running on GAE or a local developer
      // machine. In that case, the desired scopes must be passed in manually. When the code is
      // running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server.
      // See https://cloud.google.com/compute/docs/authentication for more information.
      if (client.createScopedRequired && client.createScopedRequired()) {
        // Scopes can be specified either as an array or as a single, space-delimited string.
        const scopes = ['https://www.googleapis.com/auth/cloud-platform'];
        client = client.createScoped(scopes);
      }
      return {
        client: client,
        projectId: res.projectId
      }
    }
    

    我是通过查看错误日志中的 Header 请求发现的,它的形式是:url: 'https://dataflow.googleapis.com/v1b3/projects//jobs'(注意项目和作业之间的双“//”。

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 2020-08-16
      • 2020-09-17
      • 2019-04-04
      相关资源
      最近更新 更多