google / auth
Google Auth Library for PHP
Installs: 192 310 045
Dependents: 113
Suggesters: 1
Security: 0
Stars: 1 332
Watchers: 73
Forks: 192
Open Issues: 32
Requires
- php: ^8.1
- firebase/php-jwt: ^6.0
- guzzlehttp/guzzle: ^7.4.5
- guzzlehttp/psr7: ^2.4.5
- psr/cache: ^2.0||^3.0
- psr/http-message: ^1.1||^2.0
Requires (Dev)
- guzzlehttp/promises: ^2.0
- kelvinmo/simplejwt: 0.7.1
- phpseclib/phpseclib: ^3.0.35
- phpspec/prophecy-phpunit: ^2.1
- phpunit/phpunit: ^9.6
- sebastian/comparator: >=1.2.3
- squizlabs/php_codesniffer: ^3.5
- symfony/process: ^6.0||^7.0
- webmozart/assert: ^1.11
Suggests
- phpseclib/phpseclib: May be used in place of OpenSSL for signing strings or for token management. Please require version ^2.
- dev-main
- v2.x-dev
- v1.43.0
- v1.42.0
- v1.41.0
- v1.40.0
- v1.39.0
- v1.38.0
- v1.37.1
- v1.37.0
- v1.36.0
- v1.35.0
- v1.34.0
- v1.33.0
- v1.32.1
- v1.32.0
- v1.31.0
- v1.30.0
- v1.29.1
- v1.29.0
- v1.28.0
- v1.27.0
- v1.26.0
- v1.25.0
- v1.24.0
- v1.23.1
- v1.23.0
- v1.22.0
- v1.21.1
- v1.21.0
- v1.20.1
- v1.20.0
- v1.19.1
- v1.19.0
- v1.18.0
- v1.17.0
- v1.16.0
- v1.15.2
- v1.15.1
- v1.15.0
- v1.14.3
- v1.14.2
- v1.14.1
- v1.14.0
- v1.13.0
- v1.12.1
- v1.12.0
- v1.11.1
- v1.11.0
- v1.10.0
- v1.9.0
- v1.8.0
- v1.7.1
- v1.7.0
- v1.6.1
- v1.6.0
- v1.5.2
- v1.5.1
- v1.5.0
- v1.4.0
- v1.3.3
- v1.3.2
- v1.3.1
- v1.3.0
- v1.2.1
- v1.2.0
- v1.1.0
- v1.0.1
- v1.0
- v0.11.1
- v0.11.0
- v0.10
- v0.9
- v0.8
- v0.7
- v0.6
- v0.5
- v0.4
- v0.3
- v0.2-alpha
- v0.1-alpha
- dev-http-logging
- dev-add-impersonated-service-account-credentials
- dev-release-please--branches--main
- dev-id-token-impersonation-in-tpc
- dev-logger-prototype
- dev-access-token-verify-to-use-cachedkeyset
- dev-dev-cache-keys
- dev-refactor-access-token-verify
- dev-cache-proto
- dev-release-please--branches--release-please-test-branch
- dev-release-please-test-branch
- dev-metrics-without-extra-trait
- dev-fix-phpseclib-lint
- dev-fix_style
- dev-auth-metrics-dev-all
- dev-add-property-typehints
- dev-add-retry
- dev-debug-request-logger
- dev-dev-logging-extra
- dev-logging-extra
This package is auto-updated.
Last update: 2024-11-22 16:56:08 UTC
README
- Homepage
- http://www.github.com/google/google-auth-library-php
- Reference Docs
- https://googleapis.github.io/google-auth-library-php/main/
- Authors
- Tim Emiola
- Stanley Cheung
- Brent Shaffer
- Copyright
- Copyright © 2015 Google, Inc.
- License
- Apache 2.0
Description
This is Google's officially supported PHP client library for using OAuth 2.0 authorization and authentication with Google APIs.
Installing via Composer
The recommended way to install the google auth library is through Composer.
# Install Composer curl -sS https://getcomposer.org/installer | php
Next, run the Composer command to install the latest stable version:
composer.phar require google/auth
Application Default Credentials
This library provides an implementation of Application Default Credentials (ADC) for PHP.
Application Default Credentials provides a simple way to get authorization credentials for use in calling Google APIs, and is the recommended approach to authorize calls to Cloud APIs.
Set up ADC
To use ADC, you must set it up by providing credentials. How you set up ADC depends on the environment where your code is running, and whether you are running code in a test or production environment.
For more information, see Set up Application Default Credentials.
Enable the API you want to use
Before making your API call, you must be sure the API you're calling has been
enabled. Go to APIs & Auth > APIs in the
Google Developers Console and enable the APIs you'd like to
call. For the example below, you must enable the Drive API
.
Call the APIs
As long as you update the environment variable below to point to your JSON credentials file, the following code should output a list of your Drive files.
use Google\Auth\ApplicationDefaultCredentials; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; // specify the path to your application credentials putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json'); // define the scopes for your API call $scopes = ['https://www.googleapis.com/auth/drive.readonly']; // create middleware $middleware = ApplicationDefaultCredentials::getMiddleware($scopes); $stack = HandlerStack::create(); $stack->push($middleware); // create the HTTP client $client = new Client([ 'handler' => $stack, 'base_uri' => 'https://www.googleapis.com', 'auth' => 'google_auth' // authorize all requests ]); // make the request $response = $client->get('drive/v2/files'); // show the result! print_r((string) $response->getBody());
Guzzle 5 Compatibility
If you are using Guzzle 5, replace the create middleware
and
create the HTTP Client
steps with the following:
// create the HTTP client $client = new Client([ 'base_url' => 'https://www.googleapis.com', 'auth' => 'google_auth' // authorize all requests ]); // create subscriber $subscriber = ApplicationDefaultCredentials::getSubscriber($scopes); $client->getEmitter()->attach($subscriber);
Call using an ID Token
If your application is running behind Cloud Run, or using Cloud Identity-Aware
Proxy (IAP), you will need to fetch an ID token to access your application. For
this, use the static method getIdTokenMiddleware
on
ApplicationDefaultCredentials
.
use Google\Auth\ApplicationDefaultCredentials; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; // specify the path to your application credentials putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json'); // Provide the ID token audience. This can be a Client ID associated with an IAP application, // Or the URL associated with a CloudRun App // $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com'; // $targetAudience = 'https://service-1234-uc.a.run.app'; $targetAudience = 'YOUR_ID_TOKEN_AUDIENCE'; // create middleware $middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($targetAudience); $stack = HandlerStack::create(); $stack->push($middleware); // create the HTTP client $client = new Client([ 'handler' => $stack, 'auth' => 'google_auth', // Cloud Run, IAP, or custom resource URL 'base_uri' => 'https://YOUR_PROTECTED_RESOURCE', ]); // make the request $response = $client->get('/'); // show the result! print_r((string) $response->getBody());
For invoking Cloud Run services, your service account will need the
Cloud Run Invoker
IAM permission.
For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID used when you set up your protected resource as the target audience. See how to secure your IAP app with signed headers.
Call using a specific JSON key
If you want to use a specific JSON key instead of using GOOGLE_APPLICATION_CREDENTIALS
environment variable, you can
do this:
use Google\Auth\CredentialsLoader; use Google\Auth\Middleware\AuthTokenMiddleware; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; // Define the Google Application Credentials array $jsonKey = ['key' => 'value']; // define the scopes for your API call $scopes = ['https://www.googleapis.com/auth/drive.readonly']; // Load credentials $creds = CredentialsLoader::makeCredentials($scopes, $jsonKey); // optional caching // $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache); // create middleware $middleware = new AuthTokenMiddleware($creds); $stack = HandlerStack::create(); $stack->push($middleware); // create the HTTP client $client = new Client([ 'handler' => $stack, 'base_uri' => 'https://www.googleapis.com', 'auth' => 'google_auth' // authorize all requests ]); // make the request $response = $client->get('drive/v2/files'); // show the result! print_r((string) $response->getBody());
Call using Proxy-Authorization Header
If your application is behind a proxy such as Google Cloud IAP,
and your application occupies the Authorization
request header,
you can include the ID token in a Proxy-Authorization: Bearer
header instead. If a valid ID token is found in a Proxy-Authorization
header,
IAP authorizes the request with it. After authorizing the request, IAP passes
the Authorization header to your application without processing the content.
For this, use the static method getProxyIdTokenMiddleware
on
ApplicationDefaultCredentials
.
use Google\Auth\ApplicationDefaultCredentials; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; // specify the path to your application credentials putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json'); // Provide the ID token audience. This can be a Client ID associated with an IAP application // $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com'; $targetAudience = 'YOUR_ID_TOKEN_AUDIENCE'; // create middleware $middleware = ApplicationDefaultCredentials::getProxyIdTokenMiddleware($targetAudience); $stack = HandlerStack::create(); $stack->push($middleware); // create the HTTP client $client = new Client([ 'handler' => $stack, 'auth' => ['username', 'pass'], // auth option handled by your application 'proxy_auth' => 'google_auth', ]); // make the request $response = $client->get('/'); // show the result! print_r((string) $response->getBody());
External credentials (Workload identity federation)
Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC).
Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, you can allow your workload to impersonate a service account. This lets you access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.
Follow the detailed instructions on how to Configure Workload Identity Federation.
Verifying JWTs
If you are using Google ID tokens to authenticate users, use
the Google\Auth\AccessToken
class to verify the ID token:
use Google\Auth\AccessToken; $auth = new AccessToken(); $auth->verify($idToken);
If your app is running behind Google Identity-Aware Proxy (IAP), you can verify the ID token coming from the IAP server by pointing to the appropriate certificate URL for IAP. This is because IAP signs the ID tokens with a different key than the Google Identity service:
use Google\Auth\AccessToken; $auth = new AccessToken(); $auth->verify($idToken, [ 'certsLocation' => AccessToken::IAP_CERT_URL ]);
Caching
Caching is enabled by passing a PSR-6 CacheItemPoolInterface
instance to the constructor when instantiating the credentials.
We offer some caching classes out of the box under the Google\Auth\Cache
namespace.
use Google\Auth\ApplicationDefaultCredentials; use Google\Auth\Cache\MemoryCacheItemPool; // Cache Instance $memoryCache = new MemoryCacheItemPool; // Get the credentials // From here, the credentials will cache the access token $middleware = ApplicationDefaultCredentials::getCredentials($scope, cache: $memoryCache);
FileSystemCacheItemPool Cache
The FileSystemCacheItemPool
class is a PSR-6
compliant cache that stores its
serialized objects on disk, caching data between processes and making it possible
to use data between different requests.
use Google\Auth\Cache\FileSystemCacheItemPool; use Google\Auth\ApplicationDefaultCredentials; // Create a Cache pool instance $cache = new FileSystemCacheItemPool(__DIR__ . '/cache'); // Pass your Cache to the Auth Library $credentials = ApplicationDefaultCredentials::getCredentials($scope, cache: $cache); // This token will be cached and be able to be used for the next request $token = $credentials->fetchAuthToken();
Integrating with a third party cache
You can use a third party that follows the PSR-6
interface of your choice.
// run "composer require symfony/cache" use Google\Auth\ApplicationDefaultCredentials; use Symfony\Component\Cache\Adapter\FilesystemAdapter; // Create the cache instance $filesystemCache = new FilesystemAdapter(); // Create Get the credentials $credentials = ApplicationDefaultCredentials::getCredentials($targetAudience, cache: $filesystemCache);
License
This library is licensed under Apache 2.0. Full license text is available in COPYING.
Contributing
See CONTRIBUTING.
Support
Please report bugs at the project on Github. Don't hesitate to ask questions about the client or APIs on StackOverflow.