进一步研究后,参考@ricka的回答,我决定在我的云函数中实现身份验证检查,并通过Authorization头访问令牌以JWT令牌的形式传递。
以下是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令牌,使用
jwks-rsa
来检索公钥。我使用Auth0,因此
jwks-rsa
会访问公钥列表以检索它们。
然后可以使用checkAuth
函数来保护云函数,如下所示:
exports.get = checkAuth(function (req, res) {
});
你可以在我的github库中看到这个变化,网址是
https://github.com/tnguyen14/functions-datastore/commit/a6b32704f0b0a50cd719df8c1239f993ef74dab6。
JWT / 访问令牌可以通过多种方式获取。对于Auth0,API文档可以在
https://auth0.com/docs/api/authentication#authorize-client找到。
一旦完成了这些步骤,您就可以触发云函数(如果已启用http触发器),例如:
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer access-token" \
-d '{"foo": "bar"}' \
"https://<cloud-function-endpoint>.cloudfunctions.net/get"