Skip to content

Commit a23bcef

Browse files
Sita04dandhlee
andauthored
docs(auth-samples): add API Key auth samples and tests (GoogleCloudPlatform#8455)
* docs(auth-samples): add API Key auth samples and tests * updated copyright * added authenticating with api key * lint fix * lint fix * lint fix * lint fix again! * Apply suggestions from code review Co-authored-by: Dan Lee <71398022+dandhlee@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Dan Lee <71398022+dandhlee@users.noreply.github.com> * added return docstring and removed location parameter * modified test file and lint fix * lookup api call reformat and lint fix * lint fix * Update auth/api-client/restrict_api_key_android.py * Update auth/api-client/restrict_api_key_api.py * Update auth/api-client/restrict_api_key_http.py * Update auth/api-client/restrict_api_key_ios.py * Update auth/api-client/restrict_api_key_server.py Co-authored-by: Dan Lee <71398022+dandhlee@users.noreply.github.com>
1 parent 98f37f5 commit a23bcef

12 files changed

Lines changed: 633 additions & 2 deletions

auth/api-client/api_key_test.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
import os
15+
import re
16+
17+
from _pytest.capture import CaptureFixture
18+
import google.auth.transport.requests
19+
from google.cloud.api_keys_v2 import Key
20+
import pytest
21+
22+
import authenticate_with_api_key
23+
import create_api_key
24+
import delete_api_key
25+
import lookup_api_key
26+
import restrict_api_key_android
27+
import restrict_api_key_api
28+
import restrict_api_key_http
29+
import restrict_api_key_ios
30+
import restrict_api_key_server
31+
32+
CREDENTIALS, PROJECT = google.auth.default()
33+
SERVICE_ACCOUNT_FILE = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
34+
35+
36+
@pytest.fixture(scope="module")
37+
def api_key():
38+
api_key = create_api_key.create_api_key(PROJECT)
39+
yield api_key
40+
delete_api_key.delete_api_key(PROJECT, get_key_id(api_key.name))
41+
42+
43+
def get_key_id(api_key_name: str):
44+
return api_key_name.rsplit("/")[-1]
45+
46+
47+
def test_authenticate_with_api_key(api_key: Key, capsys: CaptureFixture):
48+
authenticate_with_api_key.authenticate_with_api_key(PROJECT, api_key.key_string)
49+
out, err = capsys.readouterr()
50+
assert re.search("Successfully authenticated using the API key", out)
51+
52+
53+
def test_lookup_api_key(api_key: Key, capsys: CaptureFixture):
54+
lookup_api_key.lookup_api_key(api_key.key_string)
55+
out, err = capsys.readouterr()
56+
assert re.search(f"Successfully retrieved the API key name: {api_key.name}", out)
57+
58+
59+
def test_restrict_api_key_android(api_key: Key, capsys: CaptureFixture):
60+
restrict_api_key_android.restrict_api_key_android(PROJECT, get_key_id(api_key.name))
61+
out, err = capsys.readouterr()
62+
assert re.search(f"Successfully updated the API key: {api_key.name}", out)
63+
64+
65+
def test_restrict_api_key_api(api_key: Key, capsys: CaptureFixture):
66+
restrict_api_key_api.restrict_api_key_api(PROJECT, get_key_id(api_key.name))
67+
out, err = capsys.readouterr()
68+
assert re.search(f"Successfully updated the API key: {api_key.name}", out)
69+
70+
71+
def test_restrict_api_key_http(api_key: Key, capsys: CaptureFixture):
72+
restrict_api_key_http.restrict_api_key_http(PROJECT, get_key_id(api_key.name))
73+
out, err = capsys.readouterr()
74+
assert re.search(f"Successfully updated the API key: {api_key.name}", out)
75+
76+
77+
def test_restrict_api_key_ios(api_key: Key, capsys: CaptureFixture):
78+
restrict_api_key_ios.restrict_api_key_ios(PROJECT, get_key_id(api_key.name))
79+
out, err = capsys.readouterr()
80+
assert re.search(f"Successfully updated the API key: {api_key.name}", out)
81+
82+
83+
def test_restrict_api_key_server(api_key: Key, capsys: CaptureFixture):
84+
restrict_api_key_server.restrict_api_key_server(PROJECT, get_key_id(api_key.name))
85+
out, err = capsys.readouterr()
86+
assert re.search(f"Successfully updated the API key: {api_key.name}", out)
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_authenticate_api_key]
16+
17+
from google.cloud import language_v1
18+
19+
20+
def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
21+
"""
22+
Authenticates with an API key for Google Language service.
23+
24+
TODO(Developer): Replace these variables before running the sample.
25+
26+
Args:
27+
quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
28+
api_key_string: The API key to authenticate to the service.
29+
"""
30+
31+
# Initialize the Language Service client and set the API key and the quota project id.
32+
client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string,
33+
"quota_project_id": quota_project_id})
34+
35+
text = "Hello, world!"
36+
document = language_v1.Document(
37+
content=text, type_=language_v1.Document.Type.PLAIN_TEXT
38+
)
39+
40+
# Make a request to analyze the sentiment of the text.
41+
sentiment = client.analyze_sentiment(
42+
request={"document": document}
43+
).document_sentiment
44+
45+
print(f"Text: {text}")
46+
print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
47+
print("Successfully authenticated using the API key")
48+
49+
# [END auth_cloud_authenticate_api_key]

auth/api-client/create_api_key.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_create_api_key]
16+
17+
from google.cloud import api_keys_v2
18+
from google.cloud.api_keys_v2 import Key
19+
20+
21+
def create_api_key(project_id: str) -> Key:
22+
"""
23+
Creates and restrict an API key.
24+
25+
TODO(Developer):
26+
1. Before running this sample,
27+
set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
28+
2. Make sure you have the necessary permission to create API keys.
29+
30+
Args:
31+
project_id: Google Cloud project id.
32+
33+
Returns:
34+
response: Returns the created API Key.
35+
"""
36+
37+
# Create the API Keys client.
38+
client = api_keys_v2.ApiKeysClient()
39+
40+
key = api_keys_v2.Key()
41+
key.display_name = "My first API key"
42+
43+
# Initialize request and set arguments.
44+
request = api_keys_v2.CreateKeyRequest()
45+
request.parent = f"projects/{project_id}/locations/global"
46+
request.key = key
47+
48+
# Make the request and wait for the operation to complete.
49+
response = client.create_key(request=request).result()
50+
51+
print(f"Successfully created an API key: {response.name}")
52+
# For authenticating with the API key, use the value in "response.key_string".
53+
# To restrict the usage of this API key, use the value in "response.name".
54+
return response
55+
56+
# [END auth_cloud_create_api_key]

auth/api-client/delete_api_key.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_delete_api_key]
16+
17+
from google.cloud import api_keys_v2
18+
19+
20+
def delete_api_key(project_id: str, key_id: str) -> None:
21+
"""
22+
Deletes an API key.
23+
24+
TODO(Developer):
25+
1. Before running this sample,
26+
set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
27+
2. Make sure you have the necessary permission to delete API keys.
28+
29+
Args:
30+
project_id: Google Cloud project id that has the API key to delete.
31+
key_id: The API key id to delete.
32+
"""
33+
34+
# Create the API Keys client.
35+
client = api_keys_v2.ApiKeysClient()
36+
37+
# Initialize the delete request and set the argument.
38+
delete_key_request = api_keys_v2.DeleteKeyRequest()
39+
delete_key_request.name = f"projects/{project_id}/locations/global/keys/{key_id}"
40+
41+
# Make the request and wait for the operation to complete.
42+
result = client.delete_key(delete_key_request).result()
43+
print(f"Successfully deleted the API key: {result.name}")
44+
45+
# [END auth_cloud_delete_api_key]

auth/api-client/lookup_api_key.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_lookup_api_key]
16+
17+
from google.cloud import api_keys_v2
18+
19+
20+
def lookup_api_key(api_key_string: str) -> None:
21+
"""
22+
Retrieves name (full path) of an API key using the API key string.
23+
24+
TODO(Developer):
25+
1. Before running this sample,
26+
set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
27+
2. Make sure you have the necessary permission to view API keys.
28+
29+
Args:
30+
api_key_string: API key string to retrieve the API key name.
31+
"""
32+
33+
# Create the API Keys client.
34+
client = api_keys_v2.ApiKeysClient()
35+
36+
# Initialize the lookup request and set the API key string.
37+
lookup_key_request = api_keys_v2.LookupKeyRequest(
38+
key_string=api_key_string,
39+
# Optionally, you can also set the etag (version).
40+
# etag=etag,
41+
)
42+
43+
# Make the request and obtain the response.
44+
lookup_key_response = client.lookup_key(lookup_key_request)
45+
46+
print(f"Successfully retrieved the API key name: {lookup_key_response.name}")
47+
48+
# [END auth_cloud_lookup_api_key]
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
pytest==7.0.1
1+
pytest==7.1.2
22
mock==4.0.3

auth/api-client/requirements.txt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
11
google-api-python-client==2.47.0
22
google-auth-httplib2==0.1.0
3-
google-auth==2.6.2
3+
google-auth==2.11.0
4+
google-cloud-api-keys==0.2.0
5+
google-cloud-compute==1.5.1
6+
google-cloud-language==2.5.2
7+
google-cloud-storage==2.5.0
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_restrict_api_key_android]
16+
17+
from google.cloud import api_keys_v2
18+
from google.cloud.api_keys_v2 import Key
19+
20+
21+
def restrict_api_key_android(project_id: str, key_id: str) -> Key:
22+
"""
23+
Restricts an API key based on android applications.
24+
25+
Specifies the Android application that can use the key.
26+
27+
TODO(Developer): Replace the variables before running this sample.
28+
29+
Args:
30+
project_id: Google Cloud project id.
31+
key_id: ID of the key to restrict. This ID is auto-created during key creation.
32+
This is different from the key string. To obtain the key_id,
33+
you can also use the lookup api: client.lookup_key()
34+
35+
Returns:
36+
response: Returns the updated API Key.
37+
"""
38+
39+
# Create the API Keys client.
40+
client = api_keys_v2.ApiKeysClient()
41+
42+
# Specify the android application's package name and SHA1 fingerprint.
43+
allowed_application = api_keys_v2.AndroidApplication()
44+
allowed_application.package_name = "com.google.appname"
45+
allowed_application.sha1_fingerprint = "0873D391E987982FBBD30873D391E987982FBBD3"
46+
47+
# Restrict the API key usage by specifying the allowed applications.
48+
android_key_restriction = api_keys_v2.AndroidKeyRestrictions()
49+
android_key_restriction.allowed_applications = [allowed_application]
50+
51+
# Set the restriction(s).
52+
# For more information on API key restriction, see:
53+
# https://cloud.google.com/docs/authentication/api-keys
54+
restrictions = api_keys_v2.Restrictions()
55+
restrictions.android_key_restrictions = android_key_restriction
56+
57+
key = api_keys_v2.Key()
58+
key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
59+
key.restrictions = restrictions
60+
61+
# Initialize request and set arguments.
62+
request = api_keys_v2.UpdateKeyRequest()
63+
request.key = key
64+
request.update_mask = "restrictions"
65+
66+
# Make the request and wait for the operation to complete.
67+
response = client.update_key(request=request).result()
68+
69+
print(f"Successfully updated the API key: {response.name}")
70+
# Use response.key_string to authenticate.
71+
return response
72+
73+
# [END auth_cloud_restrict_api_key_android]

0 commit comments

Comments
 (0)