Copied!

GCECredentials supports authorization on Google Compute Engine.

It can be used to authorize requests using the AuthTokenMiddleware, but will only succeed if being run on GCE:

use Google\Auth\Credentials\GCECredentials; use Google\Auth\Middleware\AuthTokenMiddleware; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack;

$gce = new GCECredentials(); $middleware = new AuthTokenMiddleware($gce); $stack = HandlerStack::create(); $stack->push($middleware);

$client = new Client([ 'handler' => $stack, 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', 'auth' => 'google_auth' ]);

$res = $client->get('myproject/taskqueues/myqueue');

CloneableInstantiable
Constants
public Google\Auth\UpdateMetadataInterface::AUTH_METADATA_KEY = 'authorization'
public Google\Auth\Credentials\GCECredentials::cacheKey = 'GOOGLE_AUTH_PHP_GCE'
public Google\Auth\Credentials\GCECredentials::CLIENT_ID_URI_PATH = 'v1/instance/service-accounts/default/email'
 

The metadata path of the client ID.

public Google\Auth\Credentials\GCECredentials::COMPUTE_PING_CONNECTION_TIMEOUT_S = 0.5
public Google\Auth\GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN = 'googleapis.com'
public Google\Auth\CredentialsLoader::ENV_VAR = 'GOOGLE_APPLICATION_CREDENTIALS'
public Google\Auth\Credentials\GCECredentials::FLAVOR_HEADER = 'Metadata-Flavor'
 

The header whose presence indicates GCE presence.

public Google\Auth\Credentials\GCECredentials::ID_TOKEN_URI_PATH = 'v1/instance/service-accounts/default/identity'
 

The metadata path of the default id token.

public Google\Auth\Credentials\GCECredentials::MAX_COMPUTE_PING_TRIES = 3
 

Note: the explicit timeout and tries below is a workaround. The underlying issue is that resolving an unknown host on some networks will take 20-30 seconds; making this timeout short fixes the issue, but could lead to false negatives in the event that we are on GCE, but the metadata resolution was particularly slow. The latter case is "unlikely" since the expected 4-nines time is about 0.5 seconds.

This allows us to limit the total ping maximum timeout to 1.5 seconds for developer desktop scenarios.

public Google\Auth\Credentials\GCECredentials::METADATA_IP = '169.254.169.254'
 

The metadata IP address on appengine instances.

The IP is used instead of the domain 'metadata' to avoid slow responses when not on Compute Engine.

public Google\Auth\CredentialsLoader::MTLS_CERT_ENV_VAR = 'GOOGLE_API_USE_CLIENT_CERTIFICATE'
public Google\Auth\CredentialsLoader::MTLS_WELL_KNOWN_PATH = '.secureConnect/context_aware_metadata.json'
public Google\Auth\CredentialsLoader::NON_WINDOWS_WELL_KNOWN_PATH_BASE = '.config'
public Google\Auth\Credentials\GCECredentials::PROJECT_ID_URI_PATH = 'v1/project/project-id'
 

The metadata path of the project ID.

public Google\Auth\CredentialsLoader::QUOTA_PROJECT_ENV_VAR = 'GOOGLE_CLOUD_QUOTA_PROJECT'
public Google\Auth\CredentialsLoader::TOKEN_CREDENTIAL_URI = 'https://oauth2.googleapis.com/token'
public Google\Auth\Credentials\GCECredentials::TOKEN_URI_PATH = 'v1/instance/service-accounts/default/token'
 

The metadata path of the default token.

public Google\Auth\Credentials\GCECredentials::UNIVERSE_DOMAIN_URI_PATH = 'v1/universe/universe-domain'
 

The metadata path of the project ID.

public Google\Auth\CredentialsLoader::WELL_KNOWN_PATH = 'gcloud/application_default_credentials.json'
public Google\Auth\GetQuotaProjectInterface::X_GOOG_USER_PROJECT_HEADER = 'X-Goog-User-Project'
Methods
public __construct(?Google\Auth\Iam $iam = NULL, $scope = NULL, $targetAudience = NULL, $quotaProject = NULL, $serviceAccountIdentity = NULL, ?string $universeDomain = NULL)
 
  • param \Iam|null $iam [optional] An IAM instance.
  • param string|string[] $scope [optional] the scope of the access request, expressed either as an array or as a space-delimited string.
  • param string $targetAudience [optional] The audience for the ID token.
  • param string $quotaProject [optional] Specifies a project to bill for access charges associated with the request.
  • param string $serviceAccountIdentity [optional] Specify a service account identity name to use instead of "default".
  • param string|null $universeDomain [optional] Specify a universe domain to use instead of fetching one from the metadata server.
public fetchAuthToken(?callable $httpHandler = NULL, array $headers = [])
 

Implements FetchAuthTokenInterface#fetchAuthToken.

Fetches the auth tokens from the GCE metadata host if it is available. If $httpHandler is not specified a the default HttpHandler is used.

  • param callable|null $httpHandler callback which delivers psr7 request
  • param array $headers [optional] Headers to be inserted into the token endpoint request present.
  • return array { A set of auth related metadata, based on the token type.
    @type string $access_token for access tokens
    @type int    $expires_in   for access tokens
    @type string $token_type   for access tokens
    @type string $id_token     for ID tokens
    
    }
  • throws \Exception
public static Google\Auth\CredentialsLoader::fromEnv()
 

Load a JSON key from the path specified in the environment.

Load a JSON key from the path specified in the environment variable GOOGLE_APPLICATION_CREDENTIALS. Return null if GOOGLE_APPLICATION_CREDENTIALS is not specified.

  • return array|null JSON key | null
public static Google\Auth\CredentialsLoader::fromWellKnownFile()
 

Load a JSON key from a well known path.

The well known path is OS dependent:

  • windows: %APPDATA%/gcloud/application_default_credentials.json
  • others: $HOME/.config/gcloud/application_default_credentials.json

If the file does not exist, this returns null.

  • return array|null JSON key | null
public getCacheKey()
 

Returns the Cache Key for the credential token.

The format for the cache key is: TokenURI

  • return string
public getClientName(?callable $httpHandler = NULL)
 

Get the client name from GCE metadata.

Subsequent calls will return a cached value.

  • param callable|null $httpHandler callback which delivers psr7 request
  • return string
public static getClientNameUri( $serviceAccountIdentity = NULL)
 

The full uri for accessing the default service account.

  • param string $serviceAccountIdentity [optional] Specify a service account identity name to use instead of "default".
  • return string
public static Google\Auth\CredentialsLoader::getDefaultClientCertSource()
 

Gets a callable which returns the default device certification.

  • throws \UnexpectedValueException
  • return callable|null
public getLastReceivedToken()
 
  • return array|null
public getProjectId(?callable $httpHandler = NULL)
 

Fetch the default Project ID from compute engine.

Returns null if called outside GCE.

  • param callable|null $httpHandler Callback which delivers psr7 request
  • return string|null
public getQuotaProject()
 

Get the quota project used for this API request

  • return string|null
public static getTokenUri( $serviceAccountIdentity = NULL)
 

The full uri for accessing the default token.

  • param string $serviceAccountIdentity [optional] Specify a service account identity name to use instead of "default".
  • return string
public getUniverseDomain(?callable $httpHandler = NULL) : string
 

Fetch the default universe domain from the metadata server.

  • param callable|null $httpHandler Callback which delivers psr7 request
  • return string
public Google\Auth\CredentialsLoader::getUpdateMetadataFunc()
 

export a callback function which updates runtime metadata.

  • return callable updateMetadata function
  • deprecated
public static Google\Auth\CredentialsLoader::makeCredentials( $scope, array $jsonKey, $defaultScope = NULL)
 

Create a new Credentials instance.

Important: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud Platform, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information {@see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials}

  • param string|string[] $scope the scope of the access request, expressed either as an Array or as a space-delimited String.
  • param array $jsonKey the JSON credentials.
  • param string|string[] $defaultScope The default scope to use if no user-defined scopes exist, expressed either as an Array or as a space-delimited string.
  • return \ServiceAccountCredentials|\UserRefreshCredentials|\ImpersonatedServiceAccountCredentials|\ExternalAccountCredentials
public static Google\Auth\CredentialsLoader::makeHttpClient(Google\Auth\FetchAuthTokenInterface $fetcher, array $httpClientOptions = [], ?callable $httpHandler = NULL, ?callable $tokenCallback = NULL)
 

Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.

  • param \FetchAuthTokenInterface $fetcher is used to fetch the auth token
  • param array $httpClientOptions (optional) Array of request options to apply.
  • param callable|null $httpHandler (optional) http client to fetch the token.
  • param callable|null $tokenCallback (optional) function to be called when a new token is fetched.
  • return \GuzzleHttp\Client
public static Google\Auth\CredentialsLoader::makeInsecureCredentials()
 

Create a new instance of InsecureCredentials.

  • return \InsecureCredentials
public static onAppEngineFlexible()
 

Determines if this an App Engine Flexible instance, by accessing the GAE_INSTANCE environment variable.

  • return bool true if this an App Engine Flexible Instance, false otherwise
public static onGce(?callable $httpHandler = NULL)
 

Determines if this a GCE instance, by accessing the expected metadata host.

If $httpHandler is not specified a the default HttpHandler is used.

  • param callable|null $httpHandler callback which delivers psr7 request
  • return bool True if this a GCEInstance, false otherwise
public static Google\Auth\CredentialsLoader::quotaProjectFromEnv()
 

Fetch a quota project from the environment variable GOOGLE_CLOUD_QUOTA_PROJECT. Return null if GOOGLE_CLOUD_QUOTA_PROJECT is not specified.

  • return string|null
public setIsOnGce( $isOnGce)
 

Set whether or not we've already checked the GCE environment.

  • param bool $isOnGce
  • return void
public static Google\Auth\CredentialsLoader::shouldLoadClientCertSource()
 

Determines whether or not the default device certificate should be loaded.

  • return bool
public signBlob( $stringToSign, $forceOpenSsl = false, $accessToken = NULL)
 

Sign a string using the default service account private key.

This implementation uses IAM's signBlob API.

  • see https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/signBlobSignBlob
  • param string $stringToSign The string to sign.
  • param bool $forceOpenSsl [optional] Does not apply to this credentials type.
  • param string $accessToken The access token to use to sign the blob. If provided, saves a call to the metadata server for a new access token. Defaults to null.
  • return string
  • throws \Exception
public Google\Auth\CredentialsLoader::updateMetadata( $metadata, $authUri = NULL, ?callable $httpHandler = NULL)
 

Updates metadata with the authorization token.

  • param array $metadata metadata hashmap
  • param string $authUri optional auth uri
  • param callable|null $httpHandler callback which delivers psr7 request
  • return array updated metadata hashmap
Properties
protected $lastReceivedToken = NULL
 

Result of fetchAuthToken.

  • var array
protected static Google\Auth\CredentialsLoader::$metricMetadataKey = 'x-goog-api-client'
 
  • var string The header key for the observability metrics.
Methods
protected Google\Auth\CredentialsLoader::applyServiceApiUsageMetrics( $metadata)
 
  • param array $metadata The metadata to update and return.
  • return array The updated metadata.
protected Google\Auth\CredentialsLoader::applyTokenEndpointMetrics( $metadata, $authRequestType)
 
  • param array $metadata The metadata to update and return.
  • param string $authRequestType The auth request type. Possible values are 'at', 'it', 'mds'.
  • return array The updated metadata.
protected getCredType() : string
protected static Google\Auth\CredentialsLoader::getMetricsHeader( $credType = '', $authRequestType = '') : string
 
  • param string $credType [Optional] The credential type. Empty value will not add any credential type to the header. Should be one of 'sa', 'jwt', 'imp', 'mds', 'u'.
  • param string $authRequestType [Optional] The auth request type. Empty value will not add any auth request type to the header. Should be one of 'at', 'it', 'mds'.
  • return string The header value for the observability metrics.
protected static Google\Auth\CredentialsLoader::getVersion() : string
Constants
private Google\Auth\Credentials\GCECredentials::CRED_TYPE = 'mds'
private Google\Auth\Credentials\GCECredentials::GKE_PRODUCT_NAME_FILE = '/sys/class/dmi/id/product_name'
 

The Linux file which contains the product name.

private Google\Auth\Credentials\GCECredentials::PRODUCT_NAME = 'Google'
 

The Name of the product expected from the windows registry

private Google\Auth\Credentials\GCECredentials::WINDOWS_REGISTRY_KEY_NAME = 'SystemProductName'
 

The Windows registry key name for the product name

private Google\Auth\Credentials\GCECredentials::WINDOWS_REGISTRY_KEY_PATH = 'HKEY_LOCAL_MACHINE\SYSTEM\HardwareConfig\Current\'
 

The Windows Registry key path to the product name

Properties
private $clientName = NULL
 
  • var string|null
private $hasCheckedOnGce = false
 

Flag used to ensure that the onGCE test is only done once;.

  • var bool
private $iam = NULL
 
  • var \Iam|null
private $isOnGce = false
 

Flag that stores the value of the onGCE check.

  • var bool
private $projectId = NULL
 
  • var string|null
private $quotaProject = NULL
 
  • var string|null
private $serviceAccountIdentity = NULL
 
  • var string|null
private $targetAudience = NULL
 
  • var string
private $tokenUri = NULL
 
  • var string
private ?string $universeDomain
 
  • var string
Methods
private static detectResidencyLinux(string $productNameFile) : bool
private static detectResidencyWindows(string $registryProductKey) : bool
private getFromMetadata(callable $httpHandler, $uri, array $headers = [])
 

Fetch the value of a GCE metadata server URI.

  • param callable $httpHandler An HTTP Handler to deliver PSR7 requests.
  • param string $uri The metadata URI.
  • param array $headers [optional] If present, add these headers to the token endpoint request.
  • return string
private static getIdTokenUri( $serviceAccountIdentity = NULL)
 

The full uri for accesesing the default identity token.

  • param string $serviceAccountIdentity [optional] Specify a service account identity name to use instead of "default".
  • return string
private static getProjectIdUri()
 

The full uri for accessing the default project ID.

  • return string
private static getUniverseDomainUri()
 

The full uri for accessing the default universe domain.

  • return string
Properties
protected static Google\Auth\CredentialsLoader::$metricMetadataKey = 'x-goog-api-client'
 
  • var string The header key for the observability metrics.
Methods
private static detectResidencyLinux(string $productNameFile) : bool
private static detectResidencyWindows(string $registryProductKey) : bool
public static Google\Auth\CredentialsLoader::fromEnv()
 

Load a JSON key from the path specified in the environment.

Load a JSON key from the path specified in the environment variable GOOGLE_APPLICATION_CREDENTIALS. Return null if GOOGLE_APPLICATION_CREDENTIALS is not specified.

  • return array|null JSON key | null
public static Google\Auth\CredentialsLoader::fromWellKnownFile()
 

Load a JSON key from a well known path.

The well known path is OS dependent:

  • windows: %APPDATA%/gcloud/application_default_credentials.json
  • others: $HOME/.config/gcloud/application_default_credentials.json

If the file does not exist, this returns null.

  • return array|null JSON key | null
public static getClientNameUri( $serviceAccountIdentity = NULL)
 

The full uri for accessing the default service account.

  • param string $serviceAccountIdentity [optional] Specify a service account identity name to use instead of "default".
  • return string
public static Google\Auth\CredentialsLoader::getDefaultClientCertSource()
 

Gets a callable which returns the default device certification.

  • throws \UnexpectedValueException
  • return callable|null
private static getIdTokenUri( $serviceAccountIdentity = NULL)
 

The full uri for accesesing the default identity token.

  • param string $serviceAccountIdentity [optional] Specify a service account identity name to use instead of "default".
  • return string
protected static Google\Auth\CredentialsLoader::getMetricsHeader( $credType = '', $authRequestType = '') : string
 
  • param string $credType [Optional] The credential type. Empty value will not add any credential type to the header. Should be one of 'sa', 'jwt', 'imp', 'mds', 'u'.
  • param string $authRequestType [Optional] The auth request type. Empty value will not add any auth request type to the header. Should be one of 'at', 'it', 'mds'.
  • return string The header value for the observability metrics.
private static getProjectIdUri()
 

The full uri for accessing the default project ID.

  • return string
public static getTokenUri( $serviceAccountIdentity = NULL)
 

The full uri for accessing the default token.

  • param string $serviceAccountIdentity [optional] Specify a service account identity name to use instead of "default".
  • return string
private static getUniverseDomainUri()
 

The full uri for accessing the default universe domain.

  • return string
protected static Google\Auth\CredentialsLoader::getVersion() : string
public static Google\Auth\CredentialsLoader::makeCredentials( $scope, array $jsonKey, $defaultScope = NULL)
 

Create a new Credentials instance.

Important: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud Platform, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information {@see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials}

  • param string|string[] $scope the scope of the access request, expressed either as an Array or as a space-delimited String.
  • param array $jsonKey the JSON credentials.
  • param string|string[] $defaultScope The default scope to use if no user-defined scopes exist, expressed either as an Array or as a space-delimited string.
  • return \ServiceAccountCredentials|\UserRefreshCredentials|\ImpersonatedServiceAccountCredentials|\ExternalAccountCredentials
public static Google\Auth\CredentialsLoader::makeHttpClient(Google\Auth\FetchAuthTokenInterface $fetcher, array $httpClientOptions = [], ?callable $httpHandler = NULL, ?callable $tokenCallback = NULL)
 

Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.

  • param \FetchAuthTokenInterface $fetcher is used to fetch the auth token
  • param array $httpClientOptions (optional) Array of request options to apply.
  • param callable|null $httpHandler (optional) http client to fetch the token.
  • param callable|null $tokenCallback (optional) function to be called when a new token is fetched.
  • return \GuzzleHttp\Client
public static Google\Auth\CredentialsLoader::makeInsecureCredentials()
 

Create a new instance of InsecureCredentials.

  • return \InsecureCredentials
public static onAppEngineFlexible()
 

Determines if this an App Engine Flexible instance, by accessing the GAE_INSTANCE environment variable.

  • return bool true if this an App Engine Flexible Instance, false otherwise
public static onGce(?callable $httpHandler = NULL)
 

Determines if this a GCE instance, by accessing the expected metadata host.

If $httpHandler is not specified a the default HttpHandler is used.

  • param callable|null $httpHandler callback which delivers psr7 request
  • return bool True if this a GCEInstance, false otherwise
public static Google\Auth\CredentialsLoader::quotaProjectFromEnv()
 

Fetch a quota project from the environment variable GOOGLE_CLOUD_QUOTA_PROJECT. Return null if GOOGLE_CLOUD_QUOTA_PROJECT is not specified.

  • return string|null
public static Google\Auth\CredentialsLoader::shouldLoadClientCertSource()
 

Determines whether or not the default device certificate should be loaded.

  • return bool
© 2025 Bruce Wells
Search Namespaces \ Classes
Configuration