【发布时间】:2020-08-23 22:26:41
【问题描述】:
我想做的事:从我的服务器/机器调用谷歌函数并通过(简单)身份验证限制它的使用。
我使用什么: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: - 云函数 API - IAM 服务账户凭证 API - 云运行 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 功能以防止任何人使用它? (我不需要特定的安全性,只是随机用户不使用它) 在此先感谢您的帮助
【问题讨论】:
-
您是否已将
Service Account Token Creator和Service Account User添加到您的服务帐户?完整信息可以在here找到。
标签: google-cloud-platform google-cloud-functions google-authentication google-cloud-iam server-to-server