Documentation

GCECredentials extends CredentialsLoader
in package
implements SignBlobInterface, ProjectIdProviderInterface, GetQuotaProjectInterface

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');

Table of Contents

Interfaces

SignBlobInterface
Describes a class which supports signing arbitrary strings.
ProjectIdProviderInterface
Describes a Credentials object which supports fetching the project ID.
GetQuotaProjectInterface
An interface implemented by objects that can get quota projects.

Constants

cacheKey  = 'GOOGLE_AUTH_PHP_GCE'
CLIENT_ID_URI_PATH  = 'v1/instance/service-accounts/default/email'
The metadata path of the client ID.
COMPUTE_PING_CONNECTION_TIMEOUT_S  = 0.5
ENV_VAR  = 'GOOGLE_APPLICATION_CREDENTIALS'
FLAVOR_HEADER  = 'Metadata-Flavor'
The header whose presence indicates GCE presence.
ID_TOKEN_URI_PATH  = 'v1/instance/service-accounts/default/identity'
The metadata path of the default id token.
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.
METADATA_IP  = '169.254.169.254'
The metadata IP address on appengine instances.
NON_WINDOWS_WELL_KNOWN_PATH_BASE  = '.config'
PROJECT_ID_URI_PATH  = 'v1/project/project-id'
The metadata path of the project ID.
TOKEN_CREDENTIAL_URI  = 'https://oauth2.googleapis.com/token'
TOKEN_URI_PATH  = 'v1/instance/service-accounts/default/token'
The metadata path of the default token.
WELL_KNOWN_PATH  = 'gcloud/application_default_credentials.json'

Properties

$lastReceivedToken  : mixed
Result of fetchAuthToken.
$clientName  : string|null
$hasCheckedOnGce  : bool
Flag used to ensure that the onGCE test is only done once;.
$iam  : Iam|null
$isOnGce  : bool
Flag that stores the value of the onGCE check.
$projectId  : string|null
$quotaProject  : string|null
$serviceAccountIdentity  : string|null
$targetAudience  : string
$tokenUri  : string

Methods

__construct()  : mixed
fetchAuthToken()  : array<string|int, mixed>
Implements FetchAuthTokenInterface#fetchAuthToken.
fromEnv()  : array<string|int, mixed>|null
Load a JSON key from the path specified in the environment.
fromWellKnownFile()  : array<string|int, mixed>|null
Load a JSON key from a well known path.
getCacheKey()  : string
Obtains a key that can used to cache the results of #fetchAuthToken.
getClientName()  : string
Get the client name from GCE metadata.
getClientNameUri()  : string
The full uri for accessing the default service account.
getLastReceivedToken()  : array<string|int, mixed>|null
Returns an associative array with the token and expiration time.
getProjectId()  : string|null
Fetch the default Project ID from compute engine.
getQuotaProject()  : string|null
Get the quota project used for this API request
getTokenUri()  : string
The full uri for accessing the default token.
getUpdateMetadataFunc()  : array<string|int, mixed>
export a callback function which updates runtime metadata.
makeCredentials()  : ServiceAccountCredentials|UserRefreshCredentials
Create a new Credentials instance.
makeHttpClient()  : Client
Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.
makeInsecureCredentials()  : InsecureCredentials
Create a new instance of InsecureCredentials.
onAppEngineFlexible()  : bool
Determines if this an App Engine Flexible instance, by accessing the GAE_INSTANCE environment variable.
onGce()  : bool
Determines if this a GCE instance, by accessing the expected metadata host.
signBlob()  : string
Sign a string using the default service account private key.
updateMetadata()  : array<string|int, mixed>
Updates metadata with the authorization token.
getFromMetadata()  : string
Fetch the value of a GCE metadata server URI.
getGuzzleMajorVersion()  : int
Returns the currently available major Guzzle version.
getIdTokenUri()  : string
The full uri for accesesing the default identity token.
getProjectIdUri()  : string
The full uri for accessing the default project ID.
isOnWindows()  : bool
unableToReadEnv()  : string

Constants

CLIENT_ID_URI_PATH

The metadata path of the client ID.

public mixed CLIENT_ID_URI_PATH = 'v1/instance/service-accounts/default/email'

COMPUTE_PING_CONNECTION_TIMEOUT_S

public mixed COMPUTE_PING_CONNECTION_TIMEOUT_S = 0.5

FLAVOR_HEADER

The header whose presence indicates GCE presence.

public mixed FLAVOR_HEADER = 'Metadata-Flavor'

ID_TOKEN_URI_PATH

The metadata path of the default id token.

public mixed ID_TOKEN_URI_PATH = 'v1/instance/service-accounts/default/identity'

MAX_COMPUTE_PING_TRIES

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.

public mixed MAX_COMPUTE_PING_TRIES = 3

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

METADATA_IP

The metadata IP address on appengine instances.

public mixed METADATA_IP = '169.254.169.254'

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

NON_WINDOWS_WELL_KNOWN_PATH_BASE

public mixed NON_WINDOWS_WELL_KNOWN_PATH_BASE = '.config'

PROJECT_ID_URI_PATH

The metadata path of the project ID.

public mixed PROJECT_ID_URI_PATH = 'v1/project/project-id'

TOKEN_CREDENTIAL_URI

public mixed TOKEN_CREDENTIAL_URI = 'https://oauth2.googleapis.com/token'

TOKEN_URI_PATH

The metadata path of the default token.

public mixed TOKEN_URI_PATH = 'v1/instance/service-accounts/default/token'

WELL_KNOWN_PATH

public mixed WELL_KNOWN_PATH = 'gcloud/application_default_credentials.json'

Properties

$lastReceivedToken

Result of fetchAuthToken.

protected mixed $lastReceivedToken

$hasCheckedOnGce

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

private bool $hasCheckedOnGce = false

$isOnGce

Flag that stores the value of the onGCE check.

private bool $isOnGce = false

$serviceAccountIdentity

private string|null $serviceAccountIdentity

Methods

__construct()

public __construct([Iam $iam = null ][, string|array<string|int, mixed> $scope = null ][, string $targetAudience = null ][, string $quotaProject = null ][, string $serviceAccountIdentity = null ]) : mixed
Parameters
$iam : Iam = null

[optional] An IAM instance.

$scope : string|array<string|int, mixed> = null

[optional] the scope of the access request, expressed either as an array or as a space-delimited string.

$targetAudience : string = null

[optional] The audience for the ID token.

$quotaProject : string = null

[optional] Specifies a project to bill for access charges associated with the request.

$serviceAccountIdentity : string = null

[optional] Specify a service account identity name to use instead of "default".

fetchAuthToken()

Implements FetchAuthTokenInterface#fetchAuthToken.

public fetchAuthToken([callable $httpHandler = null ]) : array<string|int, mixed>

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

Parameters
$httpHandler : callable = null

callback which delivers psr7 request

Tags
throws
Exception
Return values
array<string|int, mixed>

A set of auth related metadata, based on the token type.

Access tokens have the following keys:

  • access_token (string)
  • expires_in (int)
  • token_type (string) ID tokens have the following keys:
  • id_token (string)

fromEnv()

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

public static fromEnv() : array<string|int, mixed>|null

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 values
array<string|int, mixed>|null

JSON key | null

fromWellKnownFile()

Load a JSON key from a well known path.

public static fromWellKnownFile() : array<string|int, mixed>|null

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 values
array<string|int, mixed>|null

JSON key | null

getCacheKey()

Obtains a key that can used to cache the results of #fetchAuthToken.

public getCacheKey() : string
Return values
string

getClientName()

Get the client name from GCE metadata.

public getClientName([callable $httpHandler = null ]) : string

Subsequent calls will return a cached value.

Parameters
$httpHandler : callable = null

callback which delivers psr7 request

Return values
string

getClientNameUri()

The full uri for accessing the default service account.

public static getClientNameUri([string $serviceAccountIdentity = null ]) : string
Parameters
$serviceAccountIdentity : string = null

[optional] Specify a service account identity name to use instead of "default".

Return values
string

getLastReceivedToken()

Returns an associative array with the token and expiration time.

public getLastReceivedToken() : array<string|int, mixed>|null
Return values
array<string|int, mixed>|null

getProjectId()

Fetch the default Project ID from compute engine.

public getProjectId([callable $httpHandler = null ]) : string|null

Returns null if called outside GCE.

Parameters
$httpHandler : callable = null

Callback which delivers psr7 request

Return values
string|null

getQuotaProject()

Get the quota project used for this API request

public getQuotaProject() : string|null
Return values
string|null

getTokenUri()

The full uri for accessing the default token.

public static getTokenUri([string $serviceAccountIdentity = null ]) : string
Parameters
$serviceAccountIdentity : string = null

[optional] Specify a service account identity name to use instead of "default".

Return values
string

getUpdateMetadataFunc()

export a callback function which updates runtime metadata.

public getUpdateMetadataFunc() : array<string|int, mixed>
Return values
array<string|int, mixed>

updateMetadata function

makeCredentials()

Create a new Credentials instance.

public static makeCredentials(string|array<string|int, mixed> $scope, array<string|int, mixed> $jsonKey[, string|array<string|int, mixed> $defaultScope = null ]) : ServiceAccountCredentials|UserRefreshCredentials
Parameters
$scope : string|array<string|int, mixed>

the scope of the access request, expressed either as an Array or as a space-delimited String.

$jsonKey : array<string|int, mixed>

the JSON credentials.

$defaultScope : string|array<string|int, mixed> = null

The default scope to use if no user-defined scopes exist, expressed either as an Array or as a space-delimited string.

Return values
ServiceAccountCredentials|UserRefreshCredentials

makeHttpClient()

Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.

public static makeHttpClient(FetchAuthTokenInterface $fetcher[, array<string|int, mixed> $httpClientOptions = [] ][, callable $httpHandler = null ][, callable $tokenCallback = null ]) : Client
Parameters
$fetcher : FetchAuthTokenInterface

is used to fetch the auth token

$httpClientOptions : array<string|int, mixed> = []

(optional) Array of request options to apply.

$httpHandler : callable = null

(optional) http client to fetch the token.

$tokenCallback : callable = null

(optional) function to be called when a new token is fetched.

Return values
Client

onAppEngineFlexible()

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

public static onAppEngineFlexible() : bool
Return values
bool

true if this an App Engine Flexible Instance, false otherwise

onGce()

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

public static onGce([callable $httpHandler = null ]) : bool

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

Parameters
$httpHandler : callable = null

callback which delivers psr7 request

Return values
bool

True if this a GCEInstance, false otherwise

signBlob()

Sign a string using the default service account private key.

public signBlob(string $stringToSign[, bool $forceOpenSsl = false ][, string $accessToken = null ]) : string

This implementation uses IAM's signBlob API.

Parameters
$stringToSign : string

The string to sign.

$forceOpenSsl : bool = false

[optional] Does not apply to this credentials type.

$accessToken : string = null

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.

Tags
see
https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/signBlob

SignBlob

Return values
string

updateMetadata()

Updates metadata with the authorization token.

public updateMetadata(array<string|int, mixed> $metadata[, string $authUri = null ][, callable $httpHandler = null ]) : array<string|int, mixed>
Parameters
$metadata : array<string|int, mixed>

metadata hashmap

$authUri : string = null

optional auth uri

$httpHandler : callable = null

callback which delivers psr7 request

Return values
array<string|int, mixed>

updated metadata hashmap

getFromMetadata()

Fetch the value of a GCE metadata server URI.

private getFromMetadata(callable $httpHandler, string $uri) : string
Parameters
$httpHandler : callable

An HTTP Handler to deliver PSR7 requests.

$uri : string

The metadata URI.

Return values
string

getGuzzleMajorVersion()

Returns the currently available major Guzzle version.

private static getGuzzleMajorVersion() : int
Return values
int

getIdTokenUri()

The full uri for accesesing the default identity token.

private static getIdTokenUri([string $serviceAccountIdentity = null ]) : string
Parameters
$serviceAccountIdentity : string = null

[optional] Specify a service account identity name to use instead of "default".

Return values
string

getProjectIdUri()

The full uri for accessing the default project ID.

private static getProjectIdUri() : string
Return values
string

unableToReadEnv()

private static unableToReadEnv(string $cause) : string
Parameters
$cause : string
Return values
string

        
On this page

Search results