首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何授权HTTP POST请求使用REST API执行数据流模板

如何授权HTTP POST请求使用REST API执行数据流模板
EN

Stack Overflow用户
提问于 2019-08-09 23:44:11
回答 1查看 815关注 0票数 1

我正在尝试通过NodeJS后端服务器中的REST API执行Cloud Bigtable to Cloud Storage SequenceFile模板。

我正在使用axios 0.17.1发送请求,并且我得到了401状态。我尝试按照google文档进行操作,但是我不知道如何授权HTTP请求运行数据流模板。我希望作为服务帐户进行身份验证,并且我成功地生成并下载了包含私钥的json文件。有没有人可以通过向https://dataflow.googleapis.com/v1b3/projects/[YOUR_PROJECT_ID]/templates:launch?gcsPath=gs://dataflow-templates/latest/发送HTTP POST请求的示例来帮助我

EN

回答 1

Stack Overflow用户

发布于 2019-08-15 08:13:39

您需要从您的服务帐户凭据生成jwt。可以将jwt交换为访问令牌,然后可以使用该令牌发出执行数据流作业的请求。完整示例:

代码语言:javascript
复制
import axios from "axios";
import jwt from "jsonwebtoken";
import mem from "mem";
import fs from "fs";

const loadServiceAccount = mem(function(){
    // This is a string containing service account credentials
    const serviceAccountJson = process.env.GOOGLE_APPLICATION_CREDENTIALS;
    if (!serviceAccountJson) {
      throw new Error("Missing GCP Credentials");
    }
})

const loadCredentials = mem(function() {

  loadServiceAccount();

  const credentials = JSON.parse(fs.readFileSync("key.json").toString());

  return {
    projectId: credentials.project_id,
    privateKeyId: credentials.private_key_id,
    privateKey: credentials.private_key,
    clientEmail: credentials.client_email,
  };
});

interface ProjectCredentials {
  projectId: string;
  privateKeyId: string;
  privateKey: string;
  clientEmail: string;
}

function generateJWT(params: ProjectCredentials) {
  const scope = "https://www.googleapis.com/auth/cloud-platform";
  const authUrl = "https://www.googleapis.com/oauth2/v4/token";
  const issued = new Date().getTime() / 1000;
  const expires = issued + 60;

  const payload = {
    iss: params.clientEmail,
    sub: params.clientEmail,
    aud: authUrl,
    iat: issued,
    exp: expires,
    scope: scope,
  };

  const options = {
    keyid: params.privateKeyId,
    algorithm: "RS256",
  };

  return jwt.sign(payload, params.privateKey, options);
}

async function getAccessToken(credentials: ProjectCredentials): Promise<string> {
  const jwt = generateJWT(credentials);
  const authUrl = "https://www.googleapis.com/oauth2/v4/token";
  const params = {
    grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
    assertion: jwt,
  };
  try {
    const response = await axios.post(authUrl, params);
    return response.data.access_token;
  } catch (error) {
    console.error("Failed to get access token", error);
    throw error;
  }
}

function buildTemplateParams(projectId: string, table: string) {
  return {
    jobName: `[job-name]`,
    parameters: {
      bigtableProjectId: projectId,
      bigtableInstanceId: "[table-instance]",
      bigtableTableId: table,
      outputDirectory: `[gs://your-instance]`,
      filenamePrefix: `${table}-`,
    },
    environment: {
      zone: "us-west1-a" // omit or define your own,
      tempLocation: `[gs://your-instance/temp]`,
    },
  };
}

async function backupTable(table: string) {
  console.info(`Executing backup template for table=${table}`);
  const credentials = loadCredentials();
  const { projectId } = credentials;
  const accessToken = await getAccessToken(credentials);
  const baseUrl = "https://dataflow.googleapis.com/v1b3/projects";
  const templatePath = "gs://dataflow-templates/latest/Cloud_Bigtable_to_GCS_Avro";
  const url = `${baseUrl}/${projectId}/templates:launch?gcsPath=${templatePath}`;
  const template = buildTemplateParams(projectId, table);
  try {
    const response = await axios.post(url, template, {
      headers: { Authorization: `Bearer ${accessToken}` },
    });
    console.log("GCP Response", response.data);
  } catch (error) {
    console.error(`Failed to execute template for ${table}`, error.message);
  }
}

async function run() {
  await backupTable("my-table");
}

try {
  run();
} catch (err) {
  process.exit(1);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57433397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档