我想要做什么:从我的服务器/机器调用谷歌函数并通过(简单)身份验证限制它的使用。
我使用的是:Node.js,用于身份验证的 google-auth-library库。
我做了什么/尝试了什么:
1) 在 Google Cloud Functions 中创建了一个项目
2)创建了一个简单的谷歌函数
exports.helloWorld = (req, res) => {
let message = req.query.message || req.body.message || 'Hello World!';
res.status(200).send(message);
};
3)设置我的自定义服务帐户
4) 启用的 API: - Cloud Functions API - IAM 服务帐户凭据 API - Cloud Run API - 计算引擎 API - IAM 服务帐户凭据 API
5) 授予我的服务器帐户必要的授权(项目所有者、云功能管理员、IAM 项目管理员...... (需要更多?)
6) 从我的服务帐户生成密钥并以 json 格式保存
注意:拥有 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 功能以防止任何人使用它?(我不需要特定的安全性,只是随机用户不使用它)提前感谢您的帮助