Skip to main content

Flask SDK for Axioms and OAuth2 / OpenID Connect based authentication and authorization providers.

Project description

axioms-flask-py PyPI Pepy Total Downloads

Flask SDK for OAuth2 / OpenID Connect based authentication and authorization providers (Previously designed for Axioms). Secure your Flask APIs using OAuth2 / OpenID Connect based authentication and authorization checks.

GitHub Release GitHub Actions Test Workflow Status PyPI - Version Python Wheels Python Versions GitHub last commit PyPI - Status License PyPI Downloads

Prerequisite

  • Python 3.7+
  • An OAuth2/OIDC client which can obtain access token after user's authentication and authorization and include obtained access token as bearer in Authorization header of all API request sent to Python/Flask application server.

Install SDK

Install axioms-flask-py in you Flask API project,

pip install axioms-flask-py

Documentation

Prerequisite

  • Python 3.7+
  • An Axioms client which can obtain access token after user's authentication and authorization and include obtained access token as bearer in Authorization header of all API request sent to Python/Flask application server.

Install SDK

Install axioms-flask-py in you Flask API project,

pip install axioms-flask-py

Add environment variables

Create a .env file and add following configs

Option 1: Using AXIOMS_DOMAIN (for Axioms or standard OAuth2/OIDC providers)

AXIOMS_DOMAIN=<your-axioms-slug>.axioms.io
AXIOMS_AUDIENCE=<your-axioms-resource-identifier-or-endpoint>

Option 2: Using AXIOMS_JWKS_URL (for custom JWKS endpoints)

AXIOMS_JWKS_URL=https://my-auth.domain.com/oauth2/.well-known/jwks.json
AXIOMS_AUDIENCE=<your-axioms-resource-identifier-or-endpoint>

Configuration Options:

  • AXIOMS_AUDIENCE (required): Your resource identifier or API audience
  • AXIOMS_JWKS_URL (optional): Full URL to your JWKS endpoint
  • AXIOMS_DOMAIN (optional): Your auth domain (e.g., my-auth.domain.com)

Note: You must provide either AXIOMS_JWKS_URL or AXIOMS_DOMAIN.

Claims Handling:

  • Roles are checked from roles claim, or https://{AXIOMS_DOMAIN}/claims/roles if using namespaced claims
  • Permissions are checked from permissions claim, or https://{AXIOMS_DOMAIN}/claims/permissions if using namespaced claims
  • Scopes are checked from the standard scope claim

Load environment variables

In your Flask app file (where flask app is declared) add following.

from flask_dotenv import DotEnv
env = DotEnv(app)

Register Error

In your Flask app file (where flask app is declared) add following.

from flask import jsonify
from axioms_flask.error import AxiomsError

@app.errorhandler(AxiomsError)
def handle_auth_error(ex):
    response = jsonify(ex.error)
    response.status_code = ex.status_code
    if ex.status_code == 401:
        response.headers[
            "WWW-Authenticate"
        ] = "Bearer realm='{}', error='{}', error_description='{}'".format(
            app.config["AXIOMS_DOMAIN"], ex.error["error"], ex.error["error_description"]
        )
    return response

Guard Your Flask API Views

Use following decorators to guard you API views.

Decorators Description Parameter
axioms_flask.decorators.
has_valid_access_token
Checks if API request includes a valid bearer access token as authorization header. Check performed includes: token signature validation, expiry datetime validation, and token audience validation. Should be always the first decorator on the protected or private view.
axioms_flask.decorators.
has_required_scopes
Check any of the given scopes included in scope claim of the access token. Should be after has_valid_access_token. An array of strings as conditional OR representing any of the allowed scope or scopes for the view as parameter. For instance, to check openid or profile pass ['profile', 'openid'] as parameter.
axioms_flask.decorators.
has_required_roles
Check any of the given roles included in roles claim of the access token. Should be after has_valid_access_token. An array of strings as conditional OR representing any of the allowed role or roles for the view as parameter. For instance, to check sample:role1 or sample:role2 roles you will pass ['sample:role1', 'sample:role2'] as parameter.
axioms_flask.decorators.
has_required_permissions
Check any of the given permissions included in permissions claim of the access token. Should be after has_valid_access_token. An array of strings as conditional OR representing any of the allowed permission or permissions for the view as parameter. For instance, to check sample:create or sample:update permissions you will pass ['sample:create', 'sample:update'] as parameter.

Examples

  • Check openid or profile scope present in the token
from axioms_flask.decorators import has_valid_access_token, has_required_scopes

private_api = Blueprint("private_api", __name__)

@private_api.route('/private', methods=["GET"])
@has_valid_access_token
@has_required_scopes(['openid', 'profile'])
def api_private():
    return jsonify({'message': 'All good. You are authenticated!'})
  • Check sample:role role present in the token
from axioms_flask.decorators import has_valid_access_token, has_required_roles

role_api = Blueprint("role_api", __name__)

@role_api.route("/role", methods=["GET", "POST", "PATCH", "DELETE"])
@has_valid_access_token
@has_required_roles(["sample:role"])
def sample_role():
    if request.method == 'POST':
        return jsonify({"message": "Sample created."})
    if request.method == 'PATCH':
        return jsonify({"message": "Sample updated."})
    if request.method == 'GET':
        return jsonify({"message": "Sample read."})
    if request.method == 'DELETE':
        return jsonify({"message": "Sample deleted."})
  • Check permission present in the token at API method level
from axioms_flask.decorators import has_valid_access_token, has_required_permissions

permission_api = Blueprint("permission_api", __name__)

@permission_api.route("/permission", methods=["POST"])
@has_valid_access_token
@has_required_permissions(["sample:create"])
def sample_create():
    return jsonify({"message": "Sample created."})


@permission_api.route("/permission", methods=["PATCH"])
@has_valid_access_token
@has_required_permissions(["sample:update"])
def sample_update():
    return jsonify({"message": "Sample updated."})


@permission_api.route("/permission", methods=["GET"])
@has_valid_access_token
@has_required_permissions(["sample:read"])
def sample_read():
    return jsonify({"message": "Sample read."})


@permission_api.route("/permission", methods=["DELETE"])
@has_valid_access_token
@has_required_permissions(["sample:delete"])
def sample_delete():
    return jsonify({"message": "Sample deleted."})

Flask Sample

To see a complete working example download Flask sample from our Github repository or simply deploy to heroku by clicking following button. You will need to provide Axioms domain and Axioms audience to complete deployment.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

axioms_flask_py-0.0.14rc41762485913.tar.gz (23.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

axioms_flask_py-0.0.14rc41762485913-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

Details for the file axioms_flask_py-0.0.14rc41762485913.tar.gz.

File metadata

File hashes

Hashes for axioms_flask_py-0.0.14rc41762485913.tar.gz
Algorithm Hash digest
SHA256 d5bb05105cd7dfc6eccfbaf4ea6e6c93eca5a987d40f9abc283ff24e58aaa15a
MD5 9c49ef6bbc284c7f08830c5b3db11949
BLAKE2b-256 5350e7c2f3f95f3958bf70b5d21c4a2411b52abf6bacaa80e395f4b90e8848f3

See more details on using hashes here.

Provenance

The following attestation bundles were made for axioms_flask_py-0.0.14rc41762485913.tar.gz:

Publisher: release.yml on abhishektiwari/axioms-flask-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file axioms_flask_py-0.0.14rc41762485913-py3-none-any.whl.

File metadata

File hashes

Hashes for axioms_flask_py-0.0.14rc41762485913-py3-none-any.whl
Algorithm Hash digest
SHA256 36c1e8679416012c0e1b0911b780ec33f96c93553f9d0c9b9c3fe8fc1c4d36a4
MD5 badaa83679be09257024850888616f36
BLAKE2b-256 5b9cca63761c0d9d664f4faa5a6971775ad2740b736f61f7664a4b696a2ed6b2

See more details on using hashes here.

Provenance

The following attestation bundles were made for axioms_flask_py-0.0.14rc41762485913-py3-none-any.whl:

Publisher: release.yml on abhishektiwari/axioms-flask-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page