Skip to content

Commit 51fbfe3

Browse files
authored
feat: sample for authenticating GAPIC clients with an API key (#1990)
1 parent db751a5 commit 51fbfe3

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

auth/composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"require": {
33
"google/apiclient": "^2.1",
44
"google/cloud-storage": "^1.3",
5+
"google/cloud-vision": "^1.9",
56
"google/auth":"^1.0"
67
},
78
"scripts": {

auth/src/auth_cloud_apikey.php

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
/**
3+
* Copyright 2024 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/main/auth/README.md
21+
*/
22+
23+
# [START auth_cloud_apikey]
24+
namespace Google\Cloud\Samples\Auth;
25+
26+
use Google\ApiCore\ApiException;
27+
use Google\ApiCore\InsecureCredentialsWrapper;
28+
use Google\ApiCore\PagedListResponse;
29+
use Google\Cloud\Vision\V1\Client\ProductSearchClient;
30+
use Google\Cloud\Vision\V1\ListProductsRequest;
31+
use Google\Cloud\Vision\V1\Product;
32+
33+
/**
34+
* Authenticate to a cloud API using an API key explicitly.
35+
* Note: This only works for APIs with support for API keys.
36+
*
37+
* @param string $projectId The Google Cloud project ID.
38+
* @param string $location The location name.
39+
* @param string $apiKey The API key.
40+
*/
41+
function auth_cloud_apikey(string $projectId, string $location, string $apiKey): void
42+
{
43+
$formattedParent = ProductSearchClient::locationName($projectId, $location);
44+
45+
// Create a client.
46+
$productSearchClient = new ProductSearchClient([
47+
// STEP 1: Use an insecure credentials wrapper to bypass the application default credentials.
48+
'credentials' => new InsecureCredentialsWrapper(),
49+
]);
50+
51+
// Prepare the request message.
52+
$request = (new ListProductsRequest())
53+
->setParent($formattedParent);
54+
55+
// Call the API and handle any network failures.
56+
try {
57+
/** @var PagedListResponse $response */
58+
$response = $productSearchClient->listProducts($request, [
59+
// STEP 2: Pass in the API key with each RPC call as a "Call Option"
60+
'headers' => ['x-goog-api-key' => [$apiKey]],
61+
]);
62+
63+
/** @var Product $element */
64+
foreach ($response as $element) {
65+
printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
66+
}
67+
} catch (ApiException $ex) {
68+
printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
69+
}
70+
}
71+
# [END auth_cloud_apikey]
72+
73+
// The following 2 lines are only needed to run the samples
74+
require_once __DIR__ . '/../../testing/sample_helpers.php';
75+
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

auth/test/authTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,14 @@ public function testAuthHttpExplicitCommand()
8686
]);
8787
$this->assertStringContainsString(self::$bucketName, $output);
8888
}
89+
90+
public function testAuthCloudApiKey()
91+
{
92+
$output = $this->runFunctionSnippet('auth_cloud_apikey', [
93+
'projectId' => self::$projectId,
94+
'location' => 'us-central1',
95+
'apiKey' => 'abc', // fake API key
96+
]);
97+
$this->assertStringContainsString('API_KEY_INVALID', $output);
98+
}
8999
}

0 commit comments

Comments
 (0)