Last active
March 23, 2021 11:47
-
-
Save njoyce/f13e782beeff87305e0982e9c197db3b to your computer and use it in GitHub Desktop.
Generate JWT for a Google Cloud Service Account
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
""" | |
Example of creating an authentication token using a Google Cloud Service | |
Account. This token can then be used as part of the Authorization header in the | |
HTTP request in the form `Authorization: Bearer {token}` to access | |
Signing is expensive (in terms of compute resources) so the token is valid for | |
1 hour before it expires and another must be generated. | |
""" | |
import time | |
from google.auth import crypt, jwt | |
def generate_jwt( | |
keyfile: str, | |
email: str, | |
audience: str, | |
expiry: int = 3600, | |
): | |
""" | |
@param keyfile: The path to the file containing the credentials for | |
accessing the ingest endpoints. | |
@param email: The email address of the Service Account in the keyfile. | |
@param audience: The purpose of generating the token. This string is | |
supplied by NCS. | |
@expiry: The number of seconds that the jwt token is valid for. | |
""" | |
now = int(time.time()) | |
payload = { | |
"iat": now, | |
"exp": now + expiry, | |
"iss": email, | |
"aud": audience, | |
"sub": email, | |
"email": email, | |
} | |
signer = crypt.RSASigner.from_service_account_file(keyfile) | |
token = jwt.encode(signer, payload) | |
return token.decode("utf-8") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment