使用身份验证保护 Google Cloud Functions http 触发器 [英] Secure Google Cloud Functions http trigger with auth

查看:27
本文介绍了使用身份验证保护 Google Cloud Functions http 触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天按照本指南试用 Google Cloud Functions:https://cloud.google.com/functions/docs/quickstart

I am trying out Google Cloud Functions today following this guide: https://cloud.google.com/functions/docs/quickstart

我创建了一个带有 HTTP 触发器的函数,并且能够执行 POST 请求来触发一个函数写入数据存储区.

I created a function with an HTTP trigger, and was able to perform a POST request to trigger a function to write to Datastore.

我想知道是否有办法保护这个 HTTP 端点?目前似乎它会接受来自任何地方/任何人的请求.

I was wondering if there's a way I can secure this HTTP endpoint? Currently it seems that it will accept a request from anywhere/anyone.

在谷歌搜索时,我看到大多数结果都在谈论使用 Firebase 保护事物.但是,我没有在这里使用 Firebase 服务.

When googling around, I see most results talk about securing things with Firebase. However, I am not using the Firebase service here.

我的选择是让它打开,希望没有人知道 URL 端点(默默无闻的安全性),还是在函数本身中实现我自己的身份验证检查?

Would my options be either let it open, and hope no one knows the URL endpoint (security by obscurity), or implement my own auth check in the function itself?

推荐答案

在进一步研究并从@ricka 的回答中得到提示后,我决定使用传入的 JWT 令牌对我的云函数实施身份验证检查以 Authorization 标头访问令牌的形式.

After looking into this further, and taking a hint from @ricka's answer, I have decided to implement an authentication check for my cloud functions with a JWT token passed in in the form of an Authorization header access token.

这是在 Node 中的实现:

Here's the implementation in 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 接触公钥列表以检索它们.

I use jsonwebtoken to verify the JWT token, and jwks-rsa to retrieve the public key. I use Auth0, so jwks-rsa reaches out to the list of public keys to retrieve them.

checkAuth 函数可用于保护云功能:

The checkAuth function can then be used to safeguard the cloud function as:

exports.get = checkAuth(function (req, res) {
    // do things safely here
});

您可以在 https://github.com/tnguyen14/functions-datastore/commit/a6b32704f0b0a50cd719df8c1239f993ef74dab6

可以通过多种方式检索 JWT/访问令牌.对于 Auth0,可以在 https://auth0.com/docs/api 找到 API 文档/authentication#authorize-client

The JWT / access token can be retrieved in a number of way. For Auth0, the API doc can be found at https://auth0.com/docs/api/authentication#authorize-client

一旦到位,您可以使用类似的东西触发云功能(如果您启用了 http 触发器)

Once this is in place, you can trigger the cloud function (if you have yours enabled with http trigger) with something like

curl -X POST -H "Content-Type: application/json" 
-H "Authorization: Bearer access-token" 
-d '{"foo": "bar"}' 
"https://<cloud-function-endpoint>.cloudfunctions.net/get"

这篇关于使用身份验证保护 Google Cloud Functions http 触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆