Po przeanalizowaniu tego i uzyskaniu podpowiedzi w odpowiedzi @ ricka, zdecydowałem się zaimplementować sprawdzanie autentyczności moich funkcji w chmurze za pomocą tokenu JWT przekazanego w postaci tokenu dostępu do nagłówka autoryzacji.
Oto realizacja w węźle:
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);
});
};
}
używam jsonwebtoken
zweryfikować tokenu JWT i jwks-rsa
odzyskać klucz publiczny. Używam Auth0, więc jwks-rsa
dociera do listy kluczy publicznych, aby je odzyskać.
Funkcja checkAuth
mogą być następnie wykorzystane do zabezpieczenia funkcji cloud jako:
exports.get = checkAuth(function (req, res) {
// do things safely here
});
Można zobaczyć tę zmianę w moim github repo na https://github.com/tnguyen14/functions-datastore/commit/a6b32704f0b0a50cd719df8c1239f993ef74dab6
JWT/token dostępu mogą być pobierane w sposób numer drogi. Dla Auth0, doc API można znaleźć na https://auth0.com/docs/api/authentication#authorize-client
Po to jest w miejscu, można wywołać funkcję Cloud (jeśli masz swoje włączony http spuście) z czymś jak
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer access-token" \
-d '{"foo": "bar"}' \
"https://<cloud-function-endpoint>.cloudfunctions.net/get"
Mam to samo pytanie! –
Mam ten sam problem! – Neurus
Też miałem takie same wątpliwości. Bramka interfejsu AWS API ma koncepcję klucza api.Czy jest coś podobnego w GCP – unnik