NodeJS 如何获得GCP服务帐户SignedJWT,以便我可以调用接受GCP身份验证的第三方服务

db2dz4w8  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(164)

我正在尝试获取JWT签名的GCP服务帐户,以便将其发送到启用了GCP身份验证的HashiCorp Vault进行身份验证。我正在尝试在本地运行此代码,下载GCP服务帐户密钥文件,并设置GOOGLE_APPLICATION_CREDENTIALS env属性。
下面是我的函数:

import { IAMCredentialsClient } from '@google-cloud/iam-credentials';

const getGcpSAToken = async() : Promise<string | undefined | null> => {
    
    const client = new IAMCredentialsClient();
    const nbf= Math.floor(Date.now() / 1000);
    const nat= nbf + (1000 * 60 *60);

    const signRequest = {
        name: `projects/-/serviceAccounts/${process.env['VAULT_SA']}`,
        delegates:[],
        payload : JSON.stringify({
            iss: process.env['VAULT_SA'],
            sub: process.env['VAULT_SA'],
            aud: `vault/${process.env['VAULT_ROLE']}`,
            iat: nbf,
            exp: nat
        })
    }
    const signResponse = await client.signJwt(signRequest);
    const signedJwt = signResponse[0].signedJwt;
    return signedJwt;
};

我在运行时得到这个错误:

Uncaught Error Error: 3 INVALID_ARGUMENT: Request contains an invalid argument.
    at callErrorFromStatus (c:\mcc\sf\ai-epic-int-poc\node_modules\@grpc\grpc-js\build\src\call.js:33:26)
    at onReceiveStatus (c:\mcc\sf\ai-epic-int-poc\node_modules\@grpc\grpc-js\build\src\client.js:195:52)
    at onReceiveStatus (c:\mcc\sf\ai-epic-int-poc\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:365:141)
    at onReceiveStatus (c:\mcc\sf\ai-epic-int-poc\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:328:181)
    at <anonymous> (c:\mcc\sf\ai-epic-int-poc\node_modules\@grpc\grpc-js\build\src\call-stream.js:188:78)
    at processTicksAndRejections (internal/process/task_queues:78:11)

我模仿我的组织中其他人对Java所做的事情来建模这个调用,这里的文档不是很好,我正在努力寻找一个nodejs的例子来工作。

n3ipq98p

n3ipq98p1#

你申请的令牌必须在12小时内过期,根据谷歌的图书馆。我有一些时髦的数学正在进行,我假设我的纪元时间在iatexp索赔毫秒。此外,HashiCorp不会让我们使用一个令牌,是好的超过900秒。以下代码用于为您的GCP服务帐户获取signedJWT,您可以使用该帐户登录到启用了GCP身份验证的HC Vault。

const getGcpSAToken = async() : Promise<string | undefined | null> => {

    const client = new IAMCredentialsClient();
    const nbf= Math.floor(Date.now() / 1000);
    const nat= nbf + 899; // HC vault will only accept tokens that are good for less than 900 seconds...

    const signRequest = {
        name: `projects/-/serviceAccounts/${process.env['VAULT_SA']}`,
        payload : JSON.stringify({
            iss: process.env['VAULT_SA'],
            sub: process.env['VAULT_SA'],
            aud: `vault/${process.env['VAULT_ROLE']}`,
            iat: nbf,
            exp: nat
        })
    } as protos.google.iam.credentials.v1.ISignJwtRequest;
    const [response] = await client.signJwt(signRequest);
    const signedJwt = response.signedJwt;
    return signedJwt;
};

相关问题