Sau khi xem xét thêm và lấy gợi ý từ câu trả lời @ ricka, tôi đã quyết định triển khai kiểm tra xác thực cho các chức năng đám mây của mình bằng mã thông báo JWT được chuyển vào dưới dạng mã thông báo truy cập tiêu đề ủy quyền.
Đây là việc thực hiện trong 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);
});
};
}
tôi sử dụng để xác minh jsonwebtoken
token JWT, và jwks-rsa
để lấy chìa khóa công cộng. Tôi sử dụng Auth0, vì vậy, jwks-rsa
sẽ đưa ra danh sách các khóa công khai để truy xuất chúng.
Chức năng checkAuth
sau đó có thể được sử dụng để bảo vệ các chức năng điện toán đám mây như:
exports.get = checkAuth(function (req, res) {
// do things safely here
});
Bạn có thể thấy sự thay đổi này trên repo github của tôi tại https://github.com/tnguyen14/functions-datastore/commit/a6b32704f0b0a50cd719df8c1239f993ef74dab6
JWT/access token có thể được lấy ra trong một số lượng. Đối với Auth0, doc API có thể được tìm thấy tại https://auth0.com/docs/api/authentication#authorize-client
Một khi điều này được đặt ra, bạn có thể kích hoạt các chức năng điện toán đám mây (nếu bạn có bạn kích hoạt bằng http trigger) với một cái gì đó giống như
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer access-token" \
-d '{"foo": "bar"}' \
"https://<cloud-function-endpoint>.cloudfunctions.net/get"
Tôi có cùng một câu hỏi! –
Tôi gặp vấn đề tương tự! – Neurus
Tôi cũng có cùng một nghi ngờ. Cổng API AWS có khái niệm api-key.Có điều gì tương tự trong GCP – unnik