async function validateIapHeader()

in cloud-run-iap/index.js [36:63]


async function validateIapHeader(req, res, next) {
  try {
    const token = req.header('x-goog-iap-jwt-assertion');
    if (!token) throw 'x-goog-iap-jwt-assertion header not found';
    console.log('x-goog-iap-jwt-assertion:', token);
    const oAuth2Client = new gAuth.OAuth2Client();
    const keys = await oAuth2Client.getIapPublicKeys();
    const audience = '<Audience value from IAP>';
    const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync(
      token,
      keys.pubkeys,
      audience,
      ['https://cloud.google.com/iap']
    );
    // Attach decoded email and id to the request so other code can read them.
    req.userEmail = ticket.payload.email;
    req.userId = ticket.payload.sub;
    // Hand off to the next middleware or handler.
    next();
  }
  catch(ex) {
    // Log the exception so the administrator can see it.
    console.log(ex.toString());
    // An exception probably means that the header wasn't set or that it wasn't
    // signed properly. Stop processing the request and return code 403.
    res.status(403).send('Forbidden');
  }
}