如何获取运行谷歌云功能的服务帐户的访问令牌?

问题描述 投票:0回答:1

我有一个谷歌云功能,它向 GCP 应用程序引擎管理 API 发送 PATCH 请求以修改服务。我已为云功能分配了一个服务帐户,该帐户具有修改应用程序引擎服务所需的 IAM 权限,但在测试该功能时收到 401 未经授权的错误。谷歌似乎无法自动检测到发送到应用程序引擎管理API的请求是否由该服务帐户授权,那么我如何获取运行云功能的服务帐户的访问令牌,以便我可以将其包含到api调用中?

这是我当前的功能:

functions.http('toggleFingerprintServer', async (req, res) => {
    
    //get access token of service account running this function here and attack to request below to gain access to API

    if (!req.query || !req.query.servingStatus || (req.query.servingStatus!== 'SERVING' &&  req.query.servingStatus!== 'STOPPED'))
        res.status(400).json({status: 400, message: "Status must be SERVING or STOPPED"})
    else {
        const externalRes = await fetch('https://content-appengine.googleapis.com/v1/apps/demoApp/services/fingerprint-api/versions/1?updateMask=servingStatus', {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({servingStatus: req.query.servingStatus}),
        });
        res.sendStatus(externalRes.ok ? 200 : 500);
    }
});
google-cloud-platform google-app-engine google-cloud-functions google-oauth google-cloud-iam
1个回答
0
投票

确实,您需要一个访问令牌。您可以手动获取它(使用元数据服务器并调用正确的URL),但您也可以像这样利用Google Cloud客户端库的内置解决方案

    const {GoogleAuth} = require('google-auth-library');
...
...

    const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/cloud-platform'
    });
    const token = await auth.getAccessToken();
    console.log(token);

© www.soinside.com 2019 - 2024. All rights reserved.