简体   繁体   中英

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

Context

I'm following 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 has a seemingly useful example.

The Issue

After following the resources outlined above, I get the following error:

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

Relevant Code

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();
});

The Questions

From this, I'm assuming I need to have some public key.

  1. Where do I get said public key?
  2. Where do I put said public key so that the google client is initialized with it?
  3. How can I generate an example JWT to test my endpoint?

Edits

I was able to find the source of this error in 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));
    }

However, I've verified that the kid attribute does indeed exist in the decoded object:

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

Turns out the kid was invalid and therefore threw the No pem found for envelope error. Once a valid kid was supplied, the error no longer persisted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM