Last active
September 16, 2019 18:26
-
-
Save tylertreat/ee3888faa214ec4cecd5935db756fed2 to your computer and use it in GitHub Desktop.
Example Cloud Function that makes authenticated requests to an IAP-protected resource
This file contains 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
import os | |
import google.auth | |
import google.oauth2.service_account | |
from google.auth.transport.requests import Request | |
import requests | |
IAM_SCOPE = 'https://www.googleapis.com/auth/iam' | |
OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token' | |
CLIENT_ID = os.environ['CLIENT_ID'] | |
def _get_signed_jwt(): | |
credentials, _ = google.auth.default(scopes=[IAM_SCOPE]) | |
credentials.refresh(Request()) | |
signer_email = credentials.service_account_email | |
if isinstance(credentials, google.oauth2.service_account.Credentials): | |
# If the credentials are from a service account key file, use the | |
# service account key to sign. | |
signer = credentials.signer | |
else: | |
# If it's a managed service account (Cloud Function, App Engine, GCE, | |
# etc.), we need to construct a Signer since the key isn't directly | |
# accessible. | |
signer = google.auth.iam.Signer( | |
Request(), credentials, signer_email) | |
# Create OAuth2 service account credentials using the signer and email from | |
# the environment's service account. Also set target_audience to the OAuth2 | |
# client ID used by IAP. | |
credentials = google.oauth2.service_account.Credentials( | |
signer, | |
signer_email, | |
token_uri=OAUTH_TOKEN_URI, | |
additional_claims={ | |
'target_audience': CLIENT_ID | |
} | |
) | |
return credentials._make_authorization_grant_assertion() | |
def _get_google_id_token(): | |
signed_jwt = _get_signed_jwt() | |
request = Request() | |
body = { | |
'assertion': signed_jwt, | |
'grant_type': google.oauth2._client._JWT_GRANT_TYPE, | |
} | |
token_response = google.oauth2._client._token_endpoint_request( | |
request, OAUTH_TOKEN_URI, body) | |
return token_response['id_token'] | |
def oidc_test(request): | |
# Make authenticated request to IAP-protected resource. | |
oidc_token = _get_google_id_token() | |
resp = requests.request( | |
'GET', 'https://rk-playground.appspot.com', | |
headers={'Authorization': 'Bearer {}'.format(oidc_token)}) | |
print(resp) | |
return 'made request' |
This file contains 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
google-auth | |
requests |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment