如何使用 pub sub push 实现 JWT

How do I implement JWT with pub sub push

我按照有关 pub/sub 通知的文档使用推送方法 here

而且我想通过 JWT 对我的通话进行身份验证。我看了他们的 GitHub 示例 here

app.post('/pubsub/authenticated-push', jsonBodyParser, async (req, res) => {
  // Verify that the request originates from the application.
  if (req.query.token !== PUBSUB_VERIFICATION_TOKEN) {
    res.status(400).send('Invalid request');
    return;
  }

  // Verify that the push request originates from Cloud Pub/Sub.
  try {
    // Get the Cloud Pub/Sub-generated JWT in the "Authorization" header.
    const bearer = req.header('Authorization');
    const [, token] = bearer.match(/Bearer (.*)/);
    tokens.push(token);

    // Verify and decode the JWT.
    // Note: For high volume push requests, it would save some network
    // overhead if you verify the tokens offline by decoding them using
    // Google's Public Cert; caching already seen tokens works best when
    // a large volume of messages have prompted a single push server to
    // handle them, in which case they would all share the same token for
    // a limited time window.
    const ticket = await authClient.verifyIdToken({
      idToken: token,
      audience: 'example.com',
    });

    const claim = ticket.getPayload();
    claims.push(claim);
  } catch (e) {
    res.status(400).send('Invalid token');
    return;
  }

  // The message is a unicode string encoded in base64.
  const message = Buffer.from(req.body.message.data, 'base64').toString(
    'utf-8'
  );

  messages.push(message);

  res.status(200).send();
});

但是我有一些问题。

  1. 什么是 PUBSUB_VERIFICATION_TOKEN 以及如何获取它并将其存储在我的环境中?

  2. const [ token] = bearer?.match(/Bearer (.*)/);抛出以下错误

    类型 'RegExpMatchArray | null | undefined' 必须有一个 'Symbol.iterator' 方法 returns 一个 iterator.ts(2488)

  3. 如果他们从不检查此函数中的数组是否已存在令牌/声明,为什么他们将声明和令牌推送到数组中?

我正在尝试使用 Firebase Cloud Function 来实现它,这就是我所拥有的。甚至可以缓存令牌/声明吗?

//Service account auth client
const authClient = new google.auth.JWT({
    email: android_key.client_email,
    key: android_key.private_key,
    scopes: ["https://www.googleapis.com/auth/androidpublisher"]
});

export const handlePubSub = functions.region('europe-west1').https.onRequest(async (req, res) => {

    // What is PUBSUB_VERIFICATION_TOKEN???
    if (req.query.token !== PUBSUB_VERIFICATION_TOKEN) {
        res.status(400).send('Invalid request');
        return;
    }

    try {
        const bearer = req.header('Authorization');
        const [, token] = bearer?.match(/Bearer (.*)/); //Error Type 'RegExpMatchArray | null | undefined' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)
        tokens.push(token); // Why do this? Can I do this in firebase cloud functions

        const ticket = await authClient.verifyIdToken({
            idToken: token,
        });

        const claim = ticket.getPayload();
        claims.push(claim);  // Why do this? Can I do this in firebase cloud functions
    } catch (e) {
        res.status(400).send('Invalid token');
        return;
    }

    const message = Buffer.from(req.body.message.data, 'base64').toString(
        'utf-8'
    );

    console.log(message);

    return res.status(200).json({
        statusCode: 200,
        method: req.method,
        message: 'Recieved successfully'
    });
});

What is the PUBSUB_VERIFICATION_TOKEN and how do I get it and store it in my environment?

PUBSUB_VERIFICATION_TOKEN 可以是你想要的任何值。当 运行 node:

时,最简单的设置环境变量的方法是在命令行上
PUBSUB_VERIFICATION_TOKEN=whatevertoken node app.js

比较的req.query.token也来自URL查询字符串。

GET /whatever?token=whatevertoken

Type 'RegExpMatchArray | null | undefined' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)

这是他们代码中的错误。 bearer.match可以returnundefined/null不能散入数组[, token]。该示例仅在正则表达式匹配成功时才有效。这将以普通方式解析 javascript 但打字稿会在编译时突出显示此问题。

const bearer = req.header('Authorization');
const m = /Bearer (.*)/.exec(bearer)
if (m) tokens.push(m[1])

Why do they push the claims and tokens in an array if they never check that array in this function for already existing tokens / claims?

示例评论// List of all messages received by this instance。 所以更多的是调试存储而不是功能性的东西。