我今天按照本指南试用 Google Cloud Functions:https://cloud.google.com/functions/docs/quickstart
我创建了一个带有 HTTP 触发器的函数,并且能够执行一个 POST 请求来触发一个写入数据存储区的函数。
我想知道是否有办法保护这个 HTTP 端点?目前似乎它会接受来自任何地方/任何人的请求。
在谷歌搜索时,我看到大多数结果都在谈论使用 Firebase 保护事物。但是,我没有在这里使用 Firebase 服务。
我的选择是让它打开,并希望没有人知道 URL 端点(默默无闻的安全性),还是在函数本身中实现我自己的身份验证检查?
最佳答案
在进一步研究并从@ricka 的回答中得到提示后,我决定使用以 Authorization header 访问 token 的形式传入的 JWT token 对我的云函数实现身份验证检查。
下面是 Node 中的实现:
const client = jwksClient({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: "https://<auth0-account>.auth0.com/.well-known/jwks.json"
});
function verifyToken(token, cb) {
let decodedToken;
try {
decodedToken = jwt.decode(token, {complete: true});
} catch (e) {
console.error(e);
cb(e);
return;
}
client.getSigningKey(decodedToken.header.kid, function (err, key) {
if (err) {
console.error(err);
cb(err);
return;
}
const signingKey = key.publicKey || key.rsaPublicKey;
jwt.verify(token, signingKey, function (err, decoded) {
if (err) {
console.error(err);
cb(err);
return
}
console.log(decoded);
cb(null, decoded);
});
});
}
function checkAuth (fn) {
return function (req, res) {
if (!req.headers || !req.headers.authorization) {
res.status(401).send('No authorization token found.');
return;
}
const parts = req.headers.authorization.split(' ');
if (parts.length != 2) {
res.status(401).send('Bad credential format.');
return;
}
const scheme = parts[0];
const credentials = parts[1];
if (!/^Bearer$/i.test(scheme)) {
res.status(401).send('Bad credential format.');
return;
}
verifyToken(credentials, function (err) {
if (err) {
res.status(401).send('Invalid token');
return;
}
fn(req, res);
});
};
}
我用
jsonwebtoken
验证 JWT token ,和 jwks-rsa
检索公钥。我使用 Auth0,所以 jwks-rsa
访问公钥列表以检索它们。checkAuth
然后可以使用函数来保护云函数:exports.get = checkAuth(function (req, res) {
// do things safely here
});
您可以在我的 github 存储库中看到此更改 https://github.com/tnguyen14/functions-datastore/commit/a6b32704f0b0a50cd719df8c1239f993ef74dab6
可以通过多种方式检索 JWT/访问 token 。对于 Auth0,可以在 https://auth0.com/docs/api/authentication#authorize-client 找到 API 文档
一旦到位,您可以使用类似的东西触发云功能(如果您启用了 http 触发器)
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer access-token" \
-d '{"foo": "bar"}' \
"https://<cloud-function-endpoint>.cloudfunctions.net/get"
关于security - 使用身份验证保护 Google Cloud Functions http 触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46358013/