如何生成谷歌签名的 JWT 令牌

如何使用 google-auth-library 和 node js 获取签名 JWT 令牌?

我的代码:

import { JWT } from 'google-auth-library'
import keys from './jwt.keys.json';
class SecurityServices {
    async getGoogleWebToken() {
        const client = new JWT({
            email: keys.client_email,
            key: keys.private_key,
            scopes: ['https://www.googleapis.com/auth/cloud-platform'],
        });
        const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
        const res = await client.request({ url });

        console.log(client.credentials.access_token);
        console.log(client.credentials.token_type);
        console.log(client.credentials.id_token);

    }
}

结果

访问令牌 = ya29.otherchar.......................

token_type = 持有者

id_token =未定义

正如你可以访问的令牌有一系列的“。”并且 id_token 未定义

基本上,我有一个谷歌服务帐户,我想使用在我的服务帐户 JSON 文件中找到的私钥使用 RSA-256 进行签名 JWT。

这是 java https://developers.google.com/identity/protocols/oauth2/service-account#jwt-auth 中的一个示例

谢谢

stack overflow How to generate a google signed JWT token
原文答案

答案:

作者头像

你可以试试这段代码。

/**
 * Generates signed JWT for GCP vault auth
 * @param {string} serviceAccountEmail
 * @param {string} projectId
 * @param {Object} claims
 */
const getSignedJwt = async (serviceAccountEmail, projectId, claims) => {
  const authClient = await authorize();
  const request = {
    name: `projects/${projectId}/serviceAccounts/${serviceAccountEmail}`,
    resource: {
      payload: JSON.stringify(claims),
    },
    auth: authClient,
  };
  try {
    const response = (await iam.projects.serviceAccounts.signJwt(request)).data;
    return response.signedJwt;
  } catch (err) {
    console.error(err);
  }
};

const authorize = async () => {
  const auth = new google.auth.GoogleAuth({
    scopes: ["https://www.googleapis.com/auth/cloud-platform"],
  });
  return await auth.getClient();
};

/**
 * Generates claims object for JWT
 * @param {string} roleName
 * @param {string} serviceAccountEmail
 */

const getJwtClaims = (roleName, serviceAccountEmail) => {
  const timeExp = parseInt(Date.now() / 1000) + 600;
  const claims = {
    aud: `vault/${roleName}`,
    exp: timeExp,
    sub: serviceAccountEmail,
  };
  return claims;
};