|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright 2017 Google Inc. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +/** |
| 18 | + * For instructions on how to run the full sample: |
| 19 | + * |
| 20 | + * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/auth/README.md |
| 21 | + */ |
| 22 | + |
| 23 | +# [START auth_http_explicit] |
| 24 | +namespace Google\Cloud\Samples\Auth; |
| 25 | + |
| 26 | +// Imports the Google Cloud Storage client library, Auth libraries, and Guzzle |
| 27 | +// HTTP libraries. |
| 28 | +use Google\Cloud\Storage\StorageClient; |
| 29 | +use Google\Auth\Credentials\ServiceAccountCredentials; |
| 30 | +use Google\Auth\Middleware\AuthTokenMiddleware; |
| 31 | +use GuzzleHttp\Client; |
| 32 | +use GuzzleHttp\HandlerStack; |
| 33 | + |
| 34 | +function auth_http_explicit($projectId, $serviceAccountPath) |
| 35 | +{ |
| 36 | + # Construct service account credentials using the service account key file |
| 37 | + # and Google Auth library's ServiceAccountCredentials class. |
| 38 | + $serviceAccountCredentials = new ServiceAccountCredentials( |
| 39 | + 'https://www.googleapis.com/auth/cloud-platform', |
| 40 | + $serviceAccountPath); |
| 41 | + $middleware = new AuthTokenMiddleware($serviceAccountCredentials); |
| 42 | + $stack = HandlerStack::create(); |
| 43 | + $stack->push($middleware); |
| 44 | + |
| 45 | + # Create an HTTP Client using Guzzle and pass in the credentials. |
| 46 | + $http_client = new Client([ |
| 47 | + 'handler' => $stack, |
| 48 | + 'base_uri' => 'https://www.googleapis.com/storage/v1/', |
| 49 | + 'auth' => 'google_auth' |
| 50 | + ]); |
| 51 | + |
| 52 | + # Make an authenticated API request (listing storage buckets) |
| 53 | + $response = $http_client->request('GET', 'b', ['query' =>['project'=>$projectId]]); |
| 54 | + $body_content = json_decode($response->getBody()); |
| 55 | + foreach ($body_content->items as $item) { |
| 56 | + $bucket = $item->id; |
| 57 | + printf('Bucket: %s' . PHP_EOL, $bucket); |
| 58 | + } |
| 59 | +} |
| 60 | +# [END auth_http_explicit] |
0 commit comments