PluginProbe
Gmail SMTP / trunk
Gmail SMTP vtrunk
1.2.3.21 1.2.3.20 trunk 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.9 1.2.0 1.2.3.14 1.2.3.15 1.2.3.16 1.2.3.18 1.2.3.5
gmail-smtp / google-api-php-client / vendor / google / auth / README.md

README.md in Gmail SMTP trunk, at google-api-php-client/vendor/google/auth/README.md

369 lines 12.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 # Google Auth Library for PHP
2
3 <a href="https://cloud.google.com/php/docs/reference/auth/latest">Reference Docs</a>
4
5 ## Description
6
7 This is Google's officially supported PHP client library for using OAuth 2.0
8 authorization and authentication with Google APIs.
9
10 ### Installing via Composer
11
12 The recommended way to install the google auth library is through
13 [](http://getcomposer.orgComposer](http://getcomposer.org](http://getcomposer.org).
14
15 ```bash
16 # Install Composer
17 curl -sS https://getcomposer.org/installer | php
18 ```
19
20 Next, run the Composer command to install the latest stable version:
21
22 ```bash
23 composer.phar require google/auth
24 ```
25
26 ## Application Default Credentials
27
28 This library provides an implementation of
29 [Application Default Credentials (ADC)][application default credentials] for PHP.
30
31 Application Default Credentials provides a simple way to get authorization
32 credentials for use in calling Google APIs, and is
33 the recommended approach to authorize calls to Cloud APIs.
34
35 **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an
36 external source for authentication to Google Cloud Platform, you must validate it before providing
37 it to any Google API or library. Providing an unvalidated credential configuration to Google APIs
38 can compromise the security of your systems and data. For more information, refer to
39 [Validate credential configurations from external sources][externally-sourced-credentials].
40
41 [externally-sourced-credentials]: https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
42
43 ### Set up ADC
44
45 To use ADC, you must set it up by providing credentials.
46 How you set up ADC depends on the environment where your code is running,
47 and whether you are running code in a test or production environment.
48
49 For more information, see [Set up Application Default Credentials][set-up-adc].
50
51 ### Enable the API you want to use
52
53 Before making your API call, you must be sure the API you're calling has been
54 enabled. Go to **APIs & Auth** > **APIs** in the
55 [Google Developers Console][developer console] and enable the APIs you'd like to
56 call. For the example below, you must enable the `Drive API`.
57
58 ### Call the APIs
59
60 As long as you update the environment variable below to point to *your* JSON
61 credentials file, the following code should output a list of your Drive files.
62
63 ```php
64 use Google\Auth\ApplicationDefaultCredentials;
65 use GuzzleHttp\Client;
66 use GuzzleHttp\HandlerStack;
67
68 // specify the path to your application credentials
69 putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
70
71 // define the scopes for your API call
72 $scopes = ['https://www.googleapis.com/auth/drive.readonly'];
73
74 // create middleware
75 $middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
76 $stack = HandlerStack::create();
77 $stack->push($middleware);
78
79 // create the HTTP client
80 $client = new Client([
81 'handler' => $stack,
82 'base_uri' => 'https://www.googleapis.com',
83 'auth' => 'google_auth' // authorize all requests
84 ]);
85
86 // make the request
87 $response = $client->get('drive/v2/files');
88
89 // show the result!
90 print_r((string) $response->getBody());
91 ```
92
93 ##### Guzzle 5 Compatibility
94
95 If you are using [Guzzle 5][Guzzle 5], replace the `create middleware` and
96 `create the HTTP Client` steps with the following:
97
98 ```php
99 // create the HTTP client
100 $client = new Client([
101 'base_url' => 'https://www.googleapis.com',
102 'auth' => 'google_auth' // authorize all requests
103 ]);
104
105 // create subscriber
106 $subscriber = ApplicationDefaultCredentials::getSubscriber($scopes);
107 $client->getEmitter()->attach($subscriber);
108 ```
109
110 #### Call using an ID Token
111 If your application is running behind Cloud Run, or using Cloud Identity-Aware
112 Proxy (IAP), you will need to fetch an ID token to access your application. For
113 this, use the static method `getIdTokenMiddleware` on
114 `ApplicationDefaultCredentials`.
115
116 ```php
117 use Google\Auth\ApplicationDefaultCredentials;
118 use GuzzleHttp\Client;
119 use GuzzleHttp\HandlerStack;
120
121 // specify the path to your application credentials
122 putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
123
124 // Provide the ID token audience. This can be a Client ID associated with an IAP application,
125 // Or the URL associated with a CloudRun App
126 // $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';
127 // $targetAudience = 'https://service-1234-uc.a.run.app';
128 $targetAudience = 'YOUR_ID_TOKEN_AUDIENCE';
129
130 // create middleware
131 $middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($targetAudience);
132 $stack = HandlerStack::create();
133 $stack->push($middleware);
134
135 // create the HTTP client
136 $client = new Client([
137 'handler' => $stack,
138 'auth' => 'google_auth',
139 // Cloud Run, IAP, or custom resource URL
140 'base_uri' => 'https://YOUR_PROTECTED_RESOURCE',
141 ]);
142
143 // make the request
144 $response = $client->get('/');
145
146 // show the result!
147 print_r((string) $response->getBody());
148 ```
149
150 For invoking Cloud Run services, your service account will need the
151 [](https://cloud.google.com/run/docs/authenticating/service-to-service`Cloud Run Invoker`](https://cloud.google.com/run/docs/authenticating/service-to-service](https://cloud.google.com/run/docs/authenticating/service-to-service)
152 IAM permission.
153
154 For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID
155 used when you set up your protected resource as the target audience. See how to
156 [](https://cloud.google.com/iap/docs/signed-headers-howtosecure your IAP app with signed headers](https://cloud.google.com/iap/docs/signed-headers-howto](https://cloud.google.com/iap/docs/signed-headers-howto).
157
158 #### Call using a specific JSON key
159 If you want to use a specific JSON key instead of using `GOOGLE_APPLICATION_CREDENTIALS` environment variable, you can
160 do this:
161
162 ```php
163 use Google\Auth\CredentialsLoader;
164 use Google\Auth\Middleware\AuthTokenMiddleware;
165 use GuzzleHttp\Client;
166 use GuzzleHttp\HandlerStack;
167
168 // Define the Google Application Credentials array
169 $jsonKey = ['key' => 'value'];
170
171 // define the scopes for your API call
172 $scopes = ['https://www.googleapis.com/auth/drive.readonly'];
173
174 // Load credentials from JSON containing service account credentials.
175 $creds = new ServiceAccountCredentials($scopes, $jsonKey),
176
177 // For other credentials types, create those classes explicitly using the
178 // "type" field in the JSON key, for example:
179 $creds = match ($jsonKey['type']) {
180 'service_account' => new ServiceAccountCredentials($scope, $jsonKey),
181 'authorized_user' => new UserRefreshCredentials($scope, $jsonKey),
182 default => throw new InvalidArgumentException('This application only supports service account and user account credentials'),
183 };
184
185 // optional caching
186 $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache);
187
188 // create middleware
189 $middleware = new AuthTokenMiddleware($creds);
190 $stack = HandlerStack::create();
191 $stack->push($middleware);
192
193 // create the HTTP client
194 $client = new Client([
195 'handler' => $stack,
196 'base_uri' => 'https://www.googleapis.com',
197 'auth' => 'google_auth' // authorize all requests
198 ]);
199
200 // make the request
201 $response = $client->get('drive/v2/files');
202
203 // show the result!
204 print_r((string) $response->getBody());
205
206 ```
207
208 #### Call using Proxy-Authorization Header
209 If your application is behind a proxy such as [Google Cloud IAP][iap-proxy-header],
210 and your application occupies the `Authorization` request header,
211 you can include the ID token in a `Proxy-Authorization: Bearer`
212 header instead. If a valid ID token is found in a `Proxy-Authorization` header,
213 IAP authorizes the request with it. After authorizing the request, IAP passes
214 the Authorization header to your application without processing the content.
215 For this, use the static method `getProxyIdTokenMiddleware` on
216 `ApplicationDefaultCredentials`.
217
218 ```php
219 use Google\Auth\ApplicationDefaultCredentials;
220 use GuzzleHttp\Client;
221 use GuzzleHttp\HandlerStack;
222
223 // specify the path to your application credentials
224 putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
225
226 // Provide the ID token audience. This can be a Client ID associated with an IAP application
227 // $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';
228 $targetAudience = 'YOUR_ID_TOKEN_AUDIENCE';
229
230 // create middleware
231 $middleware = ApplicationDefaultCredentials::getProxyIdTokenMiddleware($targetAudience);
232 $stack = HandlerStack::create();
233 $stack->push($middleware);
234
235 // create the HTTP client
236 $client = new Client([
237 'handler' => $stack,
238 'auth' => ['username', 'pass'], // auth option handled by your application
239 'proxy_auth' => 'google_auth',
240 ]);
241
242 // make the request
243 $response = $client->get('/');
244
245 // show the result!
246 print_r((string) $response->getBody());
247 ```
248
249 [iap-proxy-header]: https://cloud.google.com/iap/docs/authentication-howto#authenticating_from_proxy-authorization_header
250
251 #### External credentials (Workload identity federation)
252
253 Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS),
254 Microsoft Azure or any identity provider that supports OpenID Connect (OIDC).
255
256 Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud
257 resources. Using identity federation, you can allow your workload to impersonate a service account. This lets you access
258 Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.
259
260 Follow the detailed instructions on how to
261 [](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-cloudsConfigure Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-clouds](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-clouds).
262
263 #### Verifying JWTs
264
265 If you are [using Google ID tokens to authenticate users][google-id-tokens], use
266 the `Google\Auth\AccessToken` class to verify the ID token:
267
268 ```php
269 use Google\Auth\AccessToken;
270
271 $auth = new AccessToken();
272 $auth->verify($idToken);
273 ```
274
275 If your app is running behind [Google Identity-Aware Proxy][iap-id-tokens]
276 (IAP), you can verify the ID token coming from the IAP server by pointing to the
277 appropriate certificate URL for IAP. This is because IAP signs the ID
278 tokens with a different key than the Google Identity service:
279
280 ```php
281 use Google\Auth\AccessToken;
282
283 $auth = new AccessToken();
284 $auth->verify($idToken, [
285 'certsLocation' => AccessToken::IAP_CERT_URL
286 ]);
287 ```
288
289 [google-id-tokens]: https://developers.google.com/identity/sign-in/web/backend-auth
290 [iap-id-tokens]: https://cloud.google.com/iap/docs/signed-headers-howto
291
292 ## Caching
293 Caching is enabled by passing a PSR-6 `CacheItemPoolInterface`
294 instance to the constructor when instantiating the credentials.
295
296 We offer some caching classes out of the box under the `Google\Auth\Cache` namespace.
297
298 ```php
299 use Google\Auth\ApplicationDefaultCredentials;
300 use Google\Auth\Cache\MemoryCacheItemPool;
301
302 // Cache Instance
303 $memoryCache = new MemoryCacheItemPool;
304
305 // Get the credentials
306 // From here, the credentials will cache the access token
307 $middleware = ApplicationDefaultCredentials::getCredentials($scope, cache: $memoryCache);
308 ```
309
310 ### FileSystemCacheItemPool Cache
311 The `FileSystemCacheItemPool` class is a `PSR-6` compliant cache that stores its
312 serialized objects on disk, caching data between processes and making it possible
313 to use data between different requests.
314
315 ```php
316 use Google\Auth\Cache\FileSystemCacheItemPool;
317 use Google\Auth\ApplicationDefaultCredentials;
318
319 // Create a Cache pool instance
320 $cache = new FileSystemCacheItemPool(__DIR__ . '/cache');
321
322 // Pass your Cache to the Auth Library
323 $credentials = ApplicationDefaultCredentials::getCredentials($scope, cache: $cache);
324
325 // This token will be cached and be able to be used for the next request
326 $token = $credentials->fetchAuthToken();
327 ```
328
329 ### Integrating with a third party cache
330 You can use a third party that follows the `PSR-6` interface of your choice.
331
332 ```php
333 // run "composer require symfony/cache"
334 use Google\Auth\ApplicationDefaultCredentials;
335 use Symfony\Component\Cache\Adapter\FilesystemAdapter;
336
337 // Create the cache instance
338 $filesystemCache = new FilesystemAdapter();
339
340 // Create Get the credentials
341 $credentials = ApplicationDefaultCredentials::getCredentials($targetAudience, cache: $filesystemCache);
342 ```
343
344 ## License
345
346 This library is licensed under Apache 2.0. Full license text is
347 available in [COPYING][copying].
348
349 ## Contributing
350
351 See [CONTRIBUTING][contributing].
352
353 ## Support
354
355 Please
356 [](https://github.com/google/google-auth-library-php/issuesreport bugs at the project on Github](https://github.com/google/google-auth-library-php/issues](https://github.com/google/google-auth-library-php/issues). Don't
357 hesitate to
358 [](http://stackoverflow.com/questions/tagged/google-auth-library-phpask questions](http://stackoverflow.com/questions/tagged/google-auth-library-php](http://stackoverflow.com/questions/tagged/google-auth-library-php)
359 about the client or APIs on [](http://stackoverflow.comStackOverflow](http://stackoverflow.com](http://stackoverflow.com).
360
361 [google-apis-php-client]: https://github.com/google/google-api-php-client
362 [application default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials
363 [contributing]: https://github.com/google/google-auth-library-php/tree/main/.github/CONTRIBUTING.md
364 [copying]: https://github.com/google/google-auth-library-php/tree/main/COPYING
365 [Guzzle]: https://github.com/guzzle/guzzle
366 [Guzzle 5]: http://docs.guzzlephp.org/en/5.3
367 [developer console]: https://console.developers.google.com
368 [set-up-adc]: https://cloud.google.com/docs/authentication/provide-credentials-adc
369