|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +'use strict'; |
| 16 | + |
| 17 | +async function main(req) { |
| 18 | + // [START auth_validate_and_decode_bearer_token_on_express] |
| 19 | + // [START cloudrun_service_to_service_receive] |
| 20 | + const {OAuth2Client} = require('google-auth-library'); |
| 21 | + |
| 22 | + const client = new OAuth2Client(); |
| 23 | + |
| 24 | + // Inner function that parses and verifies the token. |
| 25 | + async function receiveRequestAndParseAuthHeader(request) { |
| 26 | + const authHeader = request.headers.authorization; |
| 27 | + if (authHeader) { |
| 28 | + // Split the auth type and token value from the Authorization header. |
| 29 | + const [type, token] = authHeader.split(' '); |
| 30 | + |
| 31 | + if (type.toLowerCase() === 'bearer') { |
| 32 | + // More info on verifyIdToken: |
| 33 | + // https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken-iap.js |
| 34 | + try { |
| 35 | + const ticket = await client.verifyIdToken({ |
| 36 | + idToken: token, |
| 37 | + audience: process.env.CLIENT_ID, |
| 38 | + }); |
| 39 | + const payload = ticket.getPayload(); |
| 40 | + console.log(`Hello, ${payload.email}!\n`); |
| 41 | + return; |
| 42 | + } catch (err) { |
| 43 | + console.log(`Invalid token: ${err.message}\n`); |
| 44 | + return; |
| 45 | + } |
| 46 | + } else { |
| 47 | + console.log(`Unhandled header format(${type}).\n`); |
| 48 | + return; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + console.log('Hello, anonymous user.\n'); |
| 53 | + } |
| 54 | + |
| 55 | + await receiveRequestAndParseAuthHeader(req); |
| 56 | +} |
| 57 | +// [END cloudrun_service_to_service_receive] |
| 58 | +// [END auth_validate_and_decode_bearer_token_on_express] |
| 59 | + |
| 60 | +module.exports = {main}; |
0 commit comments