Google函数HTTP触发器-服务器到具有服务帐户的服务器的身份验证问题

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

我想做什么:要从我的服务器/机器上调用google函数,并通过(简单)身份验证来限制其使用。

我使用什么:Node.js,用于身份验证的google-auth-library库。

我做了/尝试过的事情

1)在Google Cloud Functions中创建了一个项目

2)创建了一个简单的Google函数

 exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || 'Hello World!';
  res.status(200).send(message);
};

3)设置我的自定义服务帐户

4)启用的api:-云功能API-IAM服务帐户凭据API-云运行API-Compute Engine API-IAM服务帐户凭据API

5)授予我的服务器帐户必要的授权(项目所有者,云功能管理员,IAM项目管理员... (需要更多吗?)

6)从我的服务帐户生成的密钥,并将其保存为json格式

NB:具有allUser权限(无需授权),我可以毫无问题地呼叫我的端点

7)从我的项目中,我试图以这种方式验证我的功能

const { JWT } = require('google-auth-library');
const fetch = require('node-fetch');
const keys = require('./service-account-keys.json');


async function callFunction(text) {
  const url = `https://europe-west1-myFunction.cloudfunctions.net/test`;

  const client = new JWT({
    email: keys.client_email,
    keyFile: keys,
    key: keys.private_key,
    scopes: [
      'https://www.googleapis.com/auth/cloud-platform',
      'https://www.googleapis.com/auth/iam',
    ],
  });

  const res = await client.request({ url });
  const tokenInfo = await client.getTokenInfo(client.credentials.access_token);

  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${client.credentials.access_token}`,
      },
    });
    if (response.status !== 200) {
      console.log(response);
      return {};
    }
    return response.json();
  } catch (e) {
    console.error(e);
  }
} 

ℹ️如果我尝试传递不带函数名称的client.request()url(https://europe-west1-myFunction.cloudfunctions.net),我没有收到错误,但是当使用在fetch调用中获得的JWT令牌时,我收到了相同的错误。

结果

 Error: 
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>401 Unauthorized</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Unauthorized</h1>
<h2>Your client does not have permission to the requested URL <code>/test1</code>.</h2>
<h2></h2>
</body></html>

❓我该如何在没有任何保护的情况下调用google函数,以防止任何人使用它? (我不需要特定的安全性,只是随机用户不使用它)预先感谢您的任何帮助

google-cloud-platform google-cloud-functions google-authentication google-cloud-iam server-to-server
1个回答
0
投票

[当您调用私有功能(或私有Cloud Run)时,您必须使用Google签名的身份令牌

在您的代码中,您使用访问令牌

      headers: {
        Authorization: `Bearer ${client.credentials.access_token}`,
      },

当您需要请求Google Cloud API而不是您的服务时,可以访问令牌

并且Google签名很重要,因为您可以使用google auth lib轻松生成一个自签名的身份令牌,但是它不起作用

您有代码示例here,我有wrote a tool in Go,如果您想尝试一下的话

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