Skip to main content
Version: v2

Authentication

Paperbox provisions a Google Cloud service account to the API consumer which is used to sign secure JSON Web Tokens (JWT) on the consumer side, which are then sent in the requests to our API. This approach is further described here.

As an additional layer of security, our API also requires an API key, which we provision for each consumer.

import time
import google.auth
from google.auth import crypt, jwt

def generate_jwt(sa_keyfile,
sa_email='account@project-id.iam.gserviceaccount.com',
audience='your-service-name',
expiry_length=3600):

"""Generates a signed JSON Web Token using a Google API Service Account."""

now = int(time.time())

# build payload
payload = {
'iat': now,
# expires after 'expiry_length' seconds.
"exp": now + expiry_length,
# iss must match 'issuer' in the security configuration in your
# swagger spec (e.g. service account email). It can be any string.
'iss': sa_email,
# aud must be either your Endpoints service name, or match the value
# specified as the 'x-google-audience' in the OpenAPI document.
'aud': audience,
# sub and email should match the service account's email address
'sub': sa_email,
'email': sa_email
}

# sign with keyfile
signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
jwt = google.auth.jwt.encode(signer, payload)

return jwt

# Generate token
keyfile = './service-account-keyfile.json'
email = f'{TENANT}@paperbox-prd.iam.gserviceaccount.com'
audience = 'https://integration.prd.paperbox.ai'
token = generate_jwt(keyfile, email, audience).decode()