如何验证来自 Google pub/sub 推送的 JWT 令牌(未找到用于信封的 pem)

How to validate JWT token from Google pub/sub push (No pem found for envelope)

上下文

我正在关注 Google's RTDNs guide on enabling Real-Time Developer Notifications. I've successfully created the topic and subscription and have received the push notifications sent to the API that I have created. I would now like to authenticate and validate these messages. For that, I'm following this guide on Authentication and Authorization. Their developer documentation here and here 有一个看似有用的示例。

问题

按照上面列出的资源进行操作后,我收到以下错误:

Error: No pem found for envelope: {"typ":"JWT","alg":"HS256"}

相关代码

const authClient = new OAuth2Client();
// ... 
app.post('/pubsub/authenticated-push', jsonBodyParser, async (req, res) => {

  // 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 (.*)/);

    // 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.

    // verifyIdToken is failing here with the `No pem found for envelope` error
    const ticket = await authClient.verifyIdToken({
      idToken: token,
      audience: 'example.com',
    });

    // ...

  } catch (e) {
    res.status(400).send('Invalid token');
    return;
  }

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

问题

据此,我假设我需要一些 public 密钥。

  1. 我从哪里得知 public 密钥?
  2. 我应该把 public 键放在哪里,以便用它初始化 google 客户端?
  3. 如何生成示例 JWT 来测试我的端点?

编辑

我能够在 their code here 中找到此错误的来源:

    if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {
      // If this is not present, then there's no reason to attempt verification
      throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));
    }

但是,我已经验证 kid 属性确实存在于解码对象中:

{"alg":"RS256","kid":"7d680d8c70d44e947133cbd499ebc1a61c3d5abc","typ":"JWT"}

原来 kid 无效,因此抛出 No pem found for envelope 错误。一旦提供了有效的 kid,错误就不再存在。