Created
July 21, 2021 23:34
-
-
Save akkornel/1b7d7fddf4df927e50ab05a5f29be13c to your computer and use it in GitHub Desktop.
This is a Cloud Function which tells the user about the OpenID Connect ID token they used to authenticate.
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 json | |
import jwcrypto.jwk | |
import jwcrypto.jwt | |
import jwcrypto.common | |
import re | |
import requests | |
# Get the OpenID Connect configuration | |
oauth_config_url = 'https://accounts.google.com/.well-known/openid-configuration' | |
oidc_config = requests.get(oauth_config_url).json() | |
# Get the ID Token JWT signing keys | |
jwks_url = oidc_config['jwks_uri'] | |
id_token_keys = jwcrypto.jwk.JWKSet.from_json( | |
requests.get(jwks_url).text | |
) | |
def hello(request): | |
# Get the JWT token used for authentication | |
try: | |
authentication_header = request.headers['Authorization'] | |
token = re.match(r"^Bearer (.+)$", authentication_header, re.IGNORECASE)[1] | |
except KeyError: | |
print('Missing Authorization header in request') | |
return ('Missing header', 400) | |
except TypeError: | |
print(f"Could not extract token from {authentication_header}") | |
return ('Bad header', 400) | |
# Check if Google removed the signature from the ID Token. | |
# See https://cloud.google.com/run/docs/troubleshooting#signature-removed | |
if re.match(r".*\.SIGNATURE_REMOVED_BY_GOOGLE$", token) is not None: | |
print('Someone authenticated with an ID token from `gcloud auth print-identity-token`!') | |
jwt_claims = json.loads( | |
jwcrypto.common.base64url_decode( | |
re.split(r"\.", token)[1] | |
) | |
) | |
else: | |
# Validate the OpenID Connect ID Token normally. | |
try: | |
jwt = jwcrypto.jwt.JWT( | |
jwt=token, | |
key=id_token_keys, | |
algs=oidc_config['id_token_signing_alg_values_supported'] | |
) | |
except Exception as e: | |
print(f"Could not process token: {e}") | |
return ("Authentication problem", 401) | |
jwt_claims = json.loads(jwt.claims) | |
# Return a hello message to the client | |
print(f"Successful call from {jwt_claims['email']}") | |
return f"Hello, {jwt_claims['email']}! Your ID Token has an audience of {jwt_claims['aud']}" |
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
jwcrypto | |
requests |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment