Cloud IAP Client Libraries

This page shows how to get started with the Google APIs Client Libraries for the Cloud IAP API. Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Installing the client library

PHP

composer require google/apiclient

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable.

GCP Console

  1. Go to the Create service account key page in the GCP Console.

    Go to the Create Service Account Key page
  2. From the Service account drop-down list, select New service account.
  3. Enter a name into the Service account name field.
  4. From the Role drop-down list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Command line

You can run the following commands using the Cloud SDK on your local machine, or within Cloud Shell.

  1. Create the service account. Replace [NAME] with your desired service account name.

    gcloud iam service-accounts create [NAME]
  2. Grant permissions to the service account. Replace [PROJECT_ID] with your project ID.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. Replace [FILE_NAME] with a name for the key file.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Using the client library

The following example shows how to use the client library.

PHP

Read more in the PHP API Reference Documentation for the Cloud IAP Client Library.

<?php
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Cloud\Samples\Iap;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

$application = new Application('Iap');

// Create request Command.
$application->add((new Command('request'))
    ->addArgument('url', InputArgument::REQUIRED, 'The Identity-Aware Proxy-protected URL to fetch.')
    ->addArgument('clientId', InputArgument::REQUIRED, 'The client ID used by Identity-Aware Proxy.')
    ->addArgument('serviceAccountPath', InputArgument::REQUIRED, 'Path for the service account you want to use.')
    ->setDescription('Make a request to an IAP-protected resource using a service account.')
    ->setHelp(<<<EOF
The <info>%command.name%</info> command makes a request to an IAP-protected resource.
    <info>php %command.full_name%</info>

EOF
    )
    ->setCode(function ($input, $output) {
        $response = make_iap_request(
            $input->getArgument('url'),
            $input->getArgument('clientId'),
            $input->getArgument('serviceAccountPath'));
        $response_body = (string)$response->getBody();
        $output->writeln('Printing out response body:');
        $output->writeln($response_body);
    })
);

// Create a validate Command.
$application->add((new Command('validate'))
    ->addArgument('url', InputArgument::REQUIRED, 'The Identity-Aware Proxy-protected URL to fetch.')
    ->addArgument('clientId', InputArgument::REQUIRED, 'The client ID used by Identity-Aware Proxy.')
    ->addArgument('serviceAccountPath', InputArgument::REQUIRED, 'Path for the service account you want to use.')
    ->addArgument('projectNumber', InputArgument::REQUIRED, 'The project *number* for your Google Cloud project. This is returned by gcloud projects describe $PROJECT_ID or in the Project Info card in Cloud Console.')
    ->addArgument('projectId', InputArgument::REQUIRED, 'The project ID for your Google Cloud Platform project.')
    ->setDescription('Makes a request to an IAP-protected resource using a service account and then validates the JWT.')
    ->setHelp(<<<EOF
The <info>%command.name%</info> command makes a request to an IAP-protected resource and then validates the JWT.
    <info>php %command.full_name%</info>

EOF
    )
    ->setCode(function ($input, $output) {
        $response = make_iap_request(
            $input->getArgument('url'),
            $input->getArgument('clientId'),
            $input->getArgument('serviceAccountPath'));
        $response_body = (string)$response->getBody();
        $iap_jwt = explode(': ', $response_body)[1];
        $user_identity = validate_jwt_from_app_engine(
            $iap_jwt,
            $input->getArgument('projectNumber'),
            $input->getArgument('projectId'));
        $output->writeln([
            'Printing user identity information from ID token payload:',
            sprintf('sub: %s', $user_identity['sub']),
            sprintf('email: %s', $user_identity['email'])
        ]);
    })
);

if (getenv('PHPUNIT_TESTS') === '1') {
    return $application;
}

$application->run();

Additional Resources

Was this page helpful? Let us know how we did:

Send feedback about...

Identity-Aware Proxy Documentation