Protect your API on Python

Extract the Bearer Token from request header

"""requires-auth.py
"""
def get_auth_token():
 auth = request.headers.get("Authorization", None)
 if not auth:
   raise Error({ code: 'auth.authorization_header_missing', status: 401 })
 contents = auth.split()
 if len(contents) < 2
   raise Error({code: 'auth.authorization_token_invalid_format', status: 401})
 elif contents[0] != 'Bearer'
   raise Error({code: 'auth.authorization_token_type_not_supported', status: 401})
 return contents[1]

Token validation

For demonstration, we use the Flask app and jose package to create the require_auth decorator to validate the token's signature, expiration status, and required claims.

Install jose as your dependency

pip install python-jose[rsa]

Retrieve Auth’s OIDC configurations

You will need a JWK public key set and the token issuer to verify the signature and source of the received JWS token. All the public Auth Authorization Configurations can be found at https://your-auth-domain/.well-known/openid-configuration.

e.g. Call https://nightly-accounts-api.complyment.com/.well-known/openid-configuration. And locate the following two fields in the response body:

Create the authorization validation decorator using the Auth’s configurations

Apply decorator to your API

Last updated