Copied!

ServiceAccountCredentials supports authorization using a Google service account.

(cf https://developers.google.com/accounts/docs/OAuth2ServiceAccount)

It's initialized using the json key file that's downloadable from developer console, which should contain a private_key and client_email fields that it uses.

Use it with AuthTokenMiddleware to authorize http requests:

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

$sa = new ServiceAccountCredentials( 'https://www.googleapis.com/auth/taskqueue', '/path/to/your/json/key_file.json' ); $middleware = new AuthTokenMiddleware($sa); $stack = HandlerStack::create(); $stack->push($middleware);

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

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

CloneableInstantiable
Constants
public Google\Auth\UpdateMetadataInterface::AUTH_METADATA_KEY = 'authorization'
public Google\Auth\GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN = 'googleapis.com'
public Google\Auth\CredentialsLoader::ENV_VAR = 'GOOGLE_APPLICATION_CREDENTIALS'
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\CredentialsLoader::QUOTA_PROJECT_ENV_VAR = 'GOOGLE_CLOUD_QUOTA_PROJECT'
public Google\Auth\CredentialsLoader::TOKEN_CREDENTIAL_URI = 'https://oauth2.googleapis.com/token'
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( $scope, $jsonKey, $sub = NULL, $targetAudience = NULL)
 

Create a new ServiceAccountCredentials.

  • param string|string[]|null $scope the scope of the access request, expressed either as an Array or as a space-delimited String.
  • param string|array $jsonKey JSON credential file path or JSON credentials as an associative array
  • param string $sub an email address account to impersonate, in situations when the service account has been delegated domain wide access.
  • param string $targetAudience The audience for the ID token.
public fetchAuthToken(?callable $httpHandler = NULL, array $headers = [])
 
  • param callable|null $httpHandler
  • param array $headers [optional] Headers to be inserted into the token endpoint request present.
  • return array { A set of auth related metadata, containing the following
    @type string $access_token
    @type int $expires_in
    @type string $token_type
    
    }
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()
 

Return the Cache Key for the credentials.

For the cache key format is one of the following: ClientEmail.Scope[.Sub] ClientEmail.Audience[.Sub]

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

Get the client name from the keyfile.

In this case, it returns the keyfile's client_email key.

  • param callable|null $httpHandler Not used by this credentials type.
  • 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
public getPrivateKey()
 

Get the private key from the keyfile.

In this case, it returns the keyfile's private_key key, needed for JWT signing.

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

Get the project ID from the service account keyfile.

Returns null if the project ID does not exist in the keyfile.

  • param callable|null $httpHandler Not used by this credentials type.
  • return string|null
public getQuotaProject()
 

Get the quota project used for this API request

  • return string|null
public getUniverseDomain() : string
 

Get the universe domain configured in the JSON credential.

  • 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 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 setSub( $sub)
 
  • param string $sub an email address account to impersonate, in situations when the service account has been delegated domain wide access.
  • 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)
 

Sign a string using the service account private key.

  • param string $stringToSign
  • param bool $forceOpenssl Whether to use OpenSSL regardless of whether phpseclib is installed. Defaults to false.
  • return string
public 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
public useJwtAccessWithScope()
 

When called, the ServiceAccountCredentials will use an instance of ServiceAccountJwtAccessCredentials to fetch (self-sign) an access token even when only scopes are supplied. Otherwise, ServiceAccountJwtAccessCredentials is only called when no scopes and an authUrl (audience) is suppled.

  • return void
Properties
protected $auth = NULL
 

The OAuth2 instance used to conduct authorization.

  • var \OAuth2
protected static Google\Auth\CredentialsLoader::$metricMetadataKey = 'x-goog-api-client'
 
  • var string The header key for the observability metrics.
protected $projectId = NULL
 
  • var string|null
protected $quotaProject = NULL
 

The quota project associated with the JSON credentials

  • var string
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\ServiceAccountCredentials::CRED_TYPE = 'sa'
 

Used in observability metric headers

  • var string
private Google\Auth\Credentials\ServiceAccountCredentials::IAM_SCOPE = 'https://www.googleapis.com/auth/iam'
Properties
private bool $isIdTokenRequest = false
 

Whether this is an ID token request or an access token request. Used when building the metric header.

private $jwtAccessCredentials = NULL
 
  • var \ServiceAccountJwtAccessCredentials|null
private $lastReceivedJwtAccessToken = NULL
 
  • var array|null
private string $universeDomain
 
  • var string
private $useJwtAccessWithScope = false
 
  • var bool
Methods
private createJwtAccessCredentials()
 
  • return \ServiceAccountJwtAccessCredentials
private useSelfSignedJwt()
 
  • return bool
Properties
protected static Google\Auth\CredentialsLoader::$metricMetadataKey = 'x-goog-api-client'
 
  • var string The header key for the observability metrics.
Methods
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 Google\Auth\CredentialsLoader::getDefaultClientCertSource()
 

Gets a callable which returns the default device certification.

  • throws \UnexpectedValueException
  • return callable|null
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
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 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