8000 docs(auth-samples): add API Key auth samples and tests by Sita04 · Pull Request #8455 · GoogleCloudPlatform/python-docs-samples · GitHub
[go: up one dir, main page]

Skip to content

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 22 commits into from
Dec 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions auth/api-client/api_key_test.py
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)
49 changes: 49 additions & 0 deletions auth/api-client/authenticate_with_api_key.py
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,
Copy link
Contributor

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

"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]
56 changes: 56 additions & 0 deletions auth/api-client/create_api_key.py
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.
"""

# 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]
45 changes: 45 additions & 0 deletions auth/api-client/delete_api_key.py
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]
48 changes: 48 additions & 0 deletions auth/api-client/lookup_api_key.py
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]
2 changes: 1 addition & 1 deletion auth/api-client/requirements-test.txt
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
6 changes: 5 additions & 1 deletion auth/api-client/requirements.txt
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please update google-auth after googleapis/google-auth-library-python#1184 is released

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
73 changes: 73 additions & 0 deletions auth/api-client/restrict_api_key_android.py
10000
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.
"""

# 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]
Loading
0