-
Notifications
You must be signed in to change notification settings - Fork 6.6k
docs(auth-samples): add API Key auth samples and tests
#8455
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
853cd55
docs(auth-samples): add API Key auth samples and tests
Sita04 31f2280
updated copyright
Sita04 201da8b
added authenticating with api key
Sita04 67081d2
lint fix
Sita04 9b91429
lint fix
Sita04 3d6fd3d
lint fix
Sita04 400923c
lint fix again!
Sita04 8da01c9
Merge branch 'main' into samples-api-key
Sita04 79c5a2f
Merge branch 'main' into samples-api-key
Sita04 b8f0610
Apply suggestions from code review
Sita04 e59276d
Apply suggestions from code review
Sita04 0059063
added return docstring and removed location parameter
Sita04 3efa9eb
modified test file and lint fix
Sita04 4414b05
lookup api call reformat and lint fix
Sita04 d6a3fa7
lint fix
Sita04 1c5db00
Merge branch 'main' into samples-api-key
Sita04 c2ce08e
Update auth/api-client/restrict_api_key_android.py
dandhlee 143525b
Update auth/api-client/restrict_api_key_api.py
dandhlee d830bcc
Update auth/api-client/restrict_api_key_http.py
dandhlee 1f9a3f7
Update auth/api-client/restrict_api_key_ios.py
dandhlee c6bf1ee
Update auth/api-client/restrict_api_key_server.py
dandhlee 2c08e5a
Merge branch 'main' into samples-api-key
Sita04 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
# Copyright 2022 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import os | ||
import re | ||
|
||
from _pytest.capture import CaptureFixture | ||
import google.auth.transport.requests | ||
from google.cloud.api_keys_v2 import Key | ||
import pytest | ||
|
||
import authenticate_with_api_key | ||
import create_api_key | ||
import delete_api_key | ||
import lookup_api_key | ||
import restrict_api_key_android | ||
import restrict_api_key_api | ||
import restrict_api_key_http | ||
import restrict_api_key_ios | ||
import restrict_api_key_server | ||
|
||
CREDENTIALS, PROJECT = google.auth.default() | ||
SERVICE_ACCOUNT_FILE = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") | ||
|
||
|
||
@pytest.fixture(scope="module") | ||
def api_key(): | ||
api_key = create_api_key.create_api_key(PROJECT) | ||
yield api_key | ||
delete_api_key.delete_api_key(PROJECT, get_key_id(api_key.name)) | ||
|
||
|
||
def get_key_id(api_key_name: str): | ||
return api_key_name.rsplit("/")[-1] | ||
|
||
|
||
def test_authenticate_with_api_key(api_key: Key, capsys: CaptureFixture): | ||
authenticate_with_api_key.authenticate_with_api_key(PROJECT, api_key.key_string) | ||
out, err = capsys.readouterr() | ||
assert re.search("Successfully authenticated using the API key", out) | ||
|
||
|
||
def test_lookup_api_key(api_key: Key, capsys: CaptureFixture): | ||
lookup_api_key.lookup_api_key(api_key.key_string) | ||
out, err = capsys.readouterr() | ||
assert re.search(f"Successfully retrieved the API key name: {api_key.name}", out) | ||
|
||
|
||
def test_restrict_api_key_android(api_key: Key, capsys: CaptureFixture): | ||
restrict_api_key_android.restrict_api_key_android(PROJECT, get_key_id(api_key.name)) | ||
out, err = capsys.readouterr() | ||
assert re.search(f"Successfully updated the API key: {api_key.name}", out) | ||
|
||
|
||
def test_restrict_api_key_api(api_key: Key, capsys: CaptureFixture): | ||
restrict_api_key_api.restrict_api_key_api(PROJECT, get_key_id(api_key.name)) | ||
out, err = capsys.readouterr() | ||
assert re.search(f"Successfully updated the API key: {api_key.name}", out) | ||
|
||
|
||
def test_restrict_api_key_http(api_key: Key, capsys: CaptureFixture): | ||
restrict_api_key_http.restrict_api_key_http(PROJECT, get_key_id(api_key.name)) | ||
out, err = capsys.readouterr() | ||
assert re.search(f"Successfully updated the API key: {api_key.name}", out) | ||
|
||
|
||
def test_restrict_api_key_ios(api_key: Key, capsys: CaptureFixture): | ||
restrict_api_key_ios.restrict_api_key_ios(PROJECT, get_key_id(api_key.name)) | ||
out, err = capsys.readouterr() | ||
assert re.search(f"Successfully updated the API key: {api_key.name}", out) | ||
|
||
|
||
def test_restrict_api_key_server(api_key: Key, capsys: CaptureFixture): | ||
restrict_api_key_server.restrict_api_key_server(PROJECT, get_key_id(api_key.name)) | ||
out, err = capsys.readouterr() | ||
assert re.search(f"Successfully updated the API key: {api_key.name}", out) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
# Copyright 2022 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# [START auth_cloud_authenticate_api_key] | ||
|
||
from google.cloud import language_v1 | ||
|
||
|
||
def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None: | ||
""" | ||
Authenticates with an API key for Google Language service. | ||
|
||
TODO(Developer): Replace these variables before running the sample. | ||
|
||
Args: | ||
quota_project_id: Google Cloud project id that should be used for quota and billing purposes. | ||
api_key_string: The API key to authenticate to the service. | ||
""" | ||
|
||
# Initialize the Language Service client and set the API key and the quota project id. | ||
client = language_v1.LanguageServiceClient(client_options={"api_key": api_key_string, | ||
"quota_project_id": quota_project_id}) | ||
|
||
text = "Hello, world!" | ||
document = language_v1.Document( | ||
content=text, type_=language_v1.Document.Type.PLAIN_TEXT | ||
) | ||
|
||
# Make a request to analyze the sentiment of the text. | ||
sentiment = client.analyze_sentiment( | ||
request={"document": document} | ||
).document_sentiment | ||
|
||
print(f"Text: {text}") | ||
print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}") | ||
print("Successfully authenticated using the API key") | ||
|
||
# [END auth_cloud_authenticate_api_key] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
# Copyright 2022 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# [START auth_cloud_create_api_key] | ||
|
||
from google.cloud import api_keys_v2 | ||
from google.cloud.api_keys_v2 import Key | ||
|
||
|
||
def create_api_key(project_id: str) -> Key: | ||
""" | ||
Creates and restrict an API key. | ||
|
||
TODO(Developer): | ||
1. Before running this sample, | ||
set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc | ||
2. Make sure you have the necessary permission to create API keys. | ||
|
||
Args: | ||
project_id: Google Cloud project id. | ||
|
||
Returns: | ||
response: Returns the created API Key. | ||
""" | ||
Sita04 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
# Create the API Keys client. | ||
client = api_keys_v2.ApiKeysClient() | ||
|
||
key = api_keys_v2.Key() | ||
key.display_name = "My first API key" | ||
|
||
# Initialize request and set arguments. | ||
request = api_keys_v2.CreateKeyRequest() | ||
request.parent = f"projects/{project_id}/locations/global" | ||
request.key = key | ||
|
||
# Make the request and wait for the operation to complete. | ||
response = client.create_key(request=request).result() | ||
|
||
print(f"Successfully created an API key: {response.name}") | ||
# For authenticating with the API key, use the value in "response.key_string". | ||
# To r 6DAF estrict the usage of this API key, use the value in "response.name". | ||
return response | ||
|
||
# [END auth_cloud_create_api_key] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# Copyright 2022 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# [START auth_cloud_delete_api_key] | ||
|
||
from google.cloud import api_keys_v2 | ||
|
||
|
||
def delete_api_key(project_id: str, key_id: str) -> None: | ||
""" | ||
Deletes an API key. | ||
|
||
TODO(Developer): | ||
1. Before running this sample, | ||
set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc | ||
2. Make sure you have the necessary permission to delete API keys. | ||
|
||
Args: | ||
project_id: Google Cloud project id that has the API key to delete. | ||
key_id: The API key id to delete. | ||
""" | ||
|
||
# Create the API Keys client. | ||
client = api_keys_v2.ApiKeysClient() | ||
|
||
# Initialize the delete request and set the argument. | ||
delete_key_request = api_keys_v2.DeleteKeyRequest() | ||
delete_key_request.name = f"projects/{project_id}/locations/global/keys/{key_id}" | ||
|
||
# Make the request and wait for the operation to complete. | ||
result = client.delete_key(delete_key_request).result() | ||
print(f"Successfully deleted the API key: {result.name}") | ||
|
||
# [END auth_cloud_delete_api_key] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
# Copyright 2022 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# [START auth_cloud_lookup_api_key] | ||
|
||
from google.cloud import api_keys_v2 | ||
|
||
|
||
def lookup_api_key(api_key_string: str) -> None: | ||
""" | ||
Retrieves name (full path) of an API key using the API key string. | ||
|
||
TODO(Developer): | ||
1. Before running this sample, | ||
set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc | ||
2. Make sure you have the necessary permission to view API keys. | ||
|
||
Args: | ||
api_key_string: API key string to retrieve the API key name. | ||
""" | ||
|
||
# Create the API Keys client. | ||
client = api_keys_v2.ApiKeysClient() | ||
|
||
# Initialize the lookup request and set the API key string. | ||
lookup_key_request = api_keys_v2.LookupKeyRequest( | ||
key_string=api_key_string, | ||
# Optionally, you can also set the etag (version). | ||
# etag=etag, | ||
) | ||
|
||
# Make the request and obtain the response. | ||
lookup_key_response = client.lookup_key(lookup_key_request) | ||
|
||
print(f"Successfully retrieved the API key name: {lookup_key_response.name}") | ||
|
||
# [END auth_cloud_lookup_api_key] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,2 @@ | ||
pytest==7.0.1 | ||
pytest==7.1.2 | ||
mock==4.0.3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,7 @@ | ||
google-api-python-client==2.47.0 | ||
google-auth-httplib2==0.1.0 | ||
google-auth==2.6.2 | ||
google-auth==2.11.0 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please update |
||
google-cloud-api-keys==0.2.0 | ||
google-cloud-compute==1.5.1 | ||
google-cloud-language==2.5.2 | ||
google-cloud-storage==2.5.0 |
10000
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
# Copyright 2022 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# [START auth_cloud_restrict_api_key_android] | ||
|
||
from google.cloud import api_keys_v2 | ||
from google.cloud.api_keys_v2 import Key | ||
|
||
|
||
def restrict_api_key_android(project_id: str, key_id: str) -> Key: | ||
""" | ||
Restricts an API key based on android applications. | ||
|
||
Specifies the Android application that can use the key. | ||
|
||
TODO(Developer): Replace the variables before running this sample. | ||
|
||
Args: | ||
project_id: Google Cloud project id. | ||
key_id: ID of the key to restrict. This ID is auto-created during key creation. | ||
This is different from the key string. To obtain the key_id, | ||
you can also use the lookup api: client.lookup_key() | ||
|
||
Returns: | ||
response: Returns the updated API Key. | ||
Sita04 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Sita04 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
# Create the API Keys client. | ||
client = api_keys_v2.ApiKeysClient() | ||
|
||
# Specify the android application's package name and SHA1 fingerprint. | ||
allowed_application = api_keys_v2.AndroidApplication() | ||
allowed_application.package_name = "com.google.appname" | ||
allowed_application.sha1_fingerprint = "0873D391E987982FBBD30873D391E987982FBBD3" | ||
|
||
# Restrict the API key usage by specifying the allowed applications. | ||
android_key_restriction = api_keys_v2.AndroidKeyRestrictions() | ||
android_key_restriction.allowed_applications = [allowed_application] | ||
|
||
# Set the restriction(s). | ||
# For more information on API key restriction, see: | ||
# https://cloud.google.com/docs/authentication/api-keys | ||
restrictions = api_keys_v2.Restrictions() | ||
restrictions.android_key_restrictions = android_key_restriction | ||
|
||
key = api_keys_v2.Key() | ||
key.name = f"projects/{project_id}/locations/global/keys/{key_id}" | ||
key.restrictions = restrictions | ||
|
||
# Initialize request and set arguments. | ||
request = api_keys_v2.UpdateKeyRequest() | ||
request.key = key | ||
request.update_mask = "restrictions" | ||
|
||
# Make the request and wait for the operation to complete. | ||
response = client.update_key(request=request).result() | ||
|
||
print(f"Successfully updated the API key: {response.name}") | ||
# Use response.key_string to authenticate. | ||
return response | ||
|
||
# [END auth_cloud_restrict_api_key_android] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
api_key
client option won't work until googleapis/google-auth-library-python#1184 is released