Skip to main content

inuits_policy_based_auth

inuits_policy_based_auth is a python package for securing API endpoints based on policies.

Installation

Install inuits_policy_based_auth as follows:

pip install inuits-policy-based-auth

Getting Started

Instantiate the PolicyFactory in you app, for example in app.py (all examples given are based on a Python Flask app). The PolicyFactory requires a function that stores the user context for the duration of the request lifecycle. This responsibility is delegated to the API, so framework-specific implementations can handle more complex scenarios, such as multiprocess and multithreaded environments.

from flask import g
from inuits_policy_based_auth import PolicyFactory


def user_context_setter(user_context):
    g.user_context = user_context


policy_factory = PolicyFactory(user_context_setter)

Manually loading policies

Importing and registering policies can be done manually. Don't forget to set a fallback key, this ensures that policies of a specific app are applied when the app cannot be determined automatically.

from inuits_policy_based_auth.authentication.policies.token_based_policies.authlib_flask_oauth2_policy import (
    AuthlibFlaskOauth2Policy,
)
from inuits_policy_based_auth.authorization.policies.super_admin_policy import (
    SuperAdminPolicy,
)


policy_factory.register_authentication_policy("apps.[app_name]", AuthlibFlaskOauth2Policy(...))
policy_factory.register_authorization_policy("apps.[app_name]", SuperAdminPolicy())
policy_factory.set_fallback_key_for_policy_mapping("apps.[app_name]")

However, it is recommended to load policies dynamically as this will allow you to make use of the full potential of this package.

Dynamically loading policies

You can write a loader which loads policies dynamically based on a configuration file.

Example configuration file:

{
  "[app_name_1]": {
    "policies": {
      "authentication": [
        "token_based_policies.authlib_flask_oauth2_policy",
        "token_based_policies.tenant_token_roles_policy"
      ],
      "authorization": [
        "super_admin_policy",
        "scope_based_policy"
      ]
    }
  },
  "[app_name_2]": {
    "policies": {
      "authentication": [
        "token_based_policies.authlib_flask_oauth2_policy",
        "token_based_policies.tenant_token_roles_policy"
      ],
      "authorization": [
        "super_admin_policy",
        "open_data_policy"
      ]
    }
  }
}

Example policy_loader.py:

import json
import os

from importlib import import_module
from inuits_policy_based_auth import PolicyFactory
from inuits_policy_based_auth.exceptions import (
    PolicyFactoryException,
)
from logging import Logger


def load_policies(policy_factory: PolicyFactory, logger: Logger):
    apps = {}

    with open(str(os.getenv("[CONFIGURATION_FILE_NAME]")), "r") as configuration_file:
        apps = json.load(configuration_file)

    for app in apps:
        try:
            auth_type = "authentication"
            for policy_module_name in apps[app]["policies"].get(auth_type):
                policy = __get_class(app, auth_type, policy_module_name)
                policy = __instantiate_authentication_policy(
                    policy_module_name, policy, logger
                )
                policy_factory.register_authentication_policy(
                    f"apps.{app}", policy
                )

            auth_type = "authorization"
            for policy_module_name in apps[app]["policies"].get(auth_type):
                policy = __get_class(app, auth_type, policy_module_name)
                policy_factory.register_authorization_policy(
                    f"apps.{app}", policy()
                )
        except Exception as error:
            raise PolicyFactoryException(
                f"Policy factory was not configured correctly: {str(error)}"
            ).with_traceback(error.__traceback__)

    policy_factory.set_fallback_key_for_policy_mapping("apps.[app_name]")


def __get_class(app, auth_type, policy_module_name):
    locations = [
        policy_module_name,
        f"apps.{app}.policies.{auth_type}.{policy_module_name}",
        f"inuits_policy_based_auth.{auth_type}.policies.{policy_module_name}",
    ]
    for location in locations:
        try:
            module = import_module(location)
            break
        except ModuleNotFoundError:
            pass
    else:
        raise ModuleNotFoundError(f"Policy {policy_module_name} not found")

    policy_class_name = module.__name__.split(".")[-1].title().replace("_", "")
    policy = getattr(module, policy_class_name)
    return policy


def __instantiate_authentication_policy(policy_module_name, policy, logger: Logger):
    token_schema = __load_token_schema()

    if policy_module_name == "token_based_policies.authlib_flask_oauth2_policy":
        allow_anonymous_users = (
            True
            if os.getenv("ALLOW_ANONYMOUS_USERS", "false").lower() == "true"
            else False
        )
        return policy(
            logger,
            token_schema,
            os.getenv("STATIC_ISSUER"),
            os.getenv("STATIC_PUBLIC_KEY"),
            os.getenv("ALLOWED_ISSUERS"),
            allow_anonymous_users,
        )
    if policy_module_name == "token_based_policies.tenant_token_roles_policy":
        return policy(
            token_schema,
            os.getenv("ROLE_SCOPE_MAPPING", os.getenv("API_SCOPES")),
            True
            if os.getenv("ALLOW_ANONYMOUS_USERS", "false").lower() == "true"
            else False,
        )

    return policy()


def __load_token_schema() -> dict:
    token_schema_path = os.getenv(
        "TOKEN_SCHEMA", "path/to/token_schema.json"
    )
    with open(token_schema_path, "r") as token_schema:
        return json.load(token_schema)

Now you can import the loader in app.py and pass policy_factory as an argument to it.

from apps.policy_loader import load_policies
from logging import Logger


load_policies(policy_factory, Logger(""))

As you can see in these examples, dynamically loading policies will allow you to add new policies and override existing ones, which makes this package highly customizable and generic.

Custom policies

Continuing from the examples above, you can make a custom authorization policy by creating a folder policies within a specific app. Here you should create the folders authentication and authorization that will contain custom policies which you can add to your configuration. In this case we name our new policy the same as an existing one, which will override it. Each authentication policy must inherit from BaseAuthenticationPolicy and implement the abstract method authenticate, while each authorization policy must inherit from BaseAuthorizationPolicy and implement the abstract method authorize.

Example folder structure:

api
├── apps
│  ├── [app_name]
│  │  ├── policies
│  │  │  ├── authentication
│  │  │  └── authorization
│  │  │     └── open_data_policy.py
│  │  ├── ...
...
│  ├── configuration.json
│  └── policy_loader.py
...
└── app.py

Example custom open_data_policy.py:

from inuits_policy_based_auth import BaseAuthorizationPolicy


class OpenDataPolicy(BaseAuthorizationPolicy):
    def authorize(self, policy_context, _, request_context):
        request = request_context.http_request
        if request.method == "GET":
            policy_context.access_verdict = True

        return policy_context

Usage

If everything is set up correctly, you can use the apply_policies decorator as follows:

from app import policy_factory
from flask import request
from inuits_policy_based_auth import RequestContext


class Entity():
    @policy_factory.apply_policies(
        RequestContext(request, ["[scope_1]", "[scope_2]"])
    )
    def get(self):
        ...

You can also use the authenticate decorator to only apply authentication policies:

from app import policy_factory
from flask import request
from inuits_policy_based_auth import RequestContext


class Entity():
    @policy_factory.authenticate(RequestContext(request))
    def get(self):
        ...

Reusing an already authenticated user context

By default, apply_policies applies the authentication policies first and the authorization policies afterwards. If the user is already authenticated earlier in the same request, you can pass a user_context_getter to apply_policies. It is a function without arguments that returns the user context of the current request. When it returns a user context, the authentication policies are skipped and only the authorization policies are applied. When it returns None, the authentication policies are applied as usual.

Decorators are applied bottom-up, so put authenticate on the outside. It runs first and sets the user context, which apply_policies then reads through the getter.

from app import policy_factory
from flask import g, request
from inuits_policy_based_auth import RequestContext


def get_user_context():
    return g.get("user_context")


class Entity():
    @policy_factory.authenticate(RequestContext(request))
    @policy_factory.apply_policies(
        RequestContext(request, ["[scope_1]", "[scope_2]"]),
        user_context_getter=get_user_context,
    )
    def patch(self):
        ...

Warning: the getter is called on every request, not when the endpoint is defined. Only use it if the user context comes from a trusted earlier step within the same request, such as the authenticate decorator. Never return a static or shared user context, as this would skip authentication for every request.

Contributing

Do not hesitate to open issues and create pull requests.

Metadata

Release files for inuits-policy-based-auth 10.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for inuits-policy-based-auth 10.2.0
File Size Uploaded Provenance Actions
inuits_policy_based_auth-10.2.0.tar.gz 43.8 kB With provenance Details for inuits_policy_based_auth-10.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for inuits-policy-based-auth 10.2.0
File Interpreter ABI Platform Actions
inuits_policy_based_auth-10.2.0-py3-none-any.whl Python 3 none any Details for inuits_policy_based_auth-10.2.0-py3-none-any.whl

Total release size: 98.5 kB

Release files / inuits_policy_based_auth-10.2.0.tar.gz

Download URL inuits_policy_based_auth-10.2.0.tar.gz
Size 43.8 kB
Tags Source
SHA-256 checksum
How to use checksums
6508373ce59b2e5666307dc935c29dce44ceebf1668b93cda2f8e50463de371d
BLAKE2b-256 checksum
How to use checksums
8faefe4d8ae32d2d6ea22d4f66b2fbc9462c134ed0bc0f6c1ff5449d72f4dc3b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Release files / inuits_policy_based_auth-10.2.0-py3-none-any.whl

Download URL inuits_policy_based_auth-10.2.0-py3-none-any.whl
Size 54.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d8393a9812cd20baee68b0b25b5b99e7bd2537a3cbc0a3620a6f969901dfd7d1
BLAKE2b-256 checksum
How to use checksums
18c80fd6407b8e1f064308dd750a5d01fa910002cffc05835a694c17dc6ac7a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Security for inuits-policy-based-auth 10.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for inuits_policy_based_auth-10.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

10.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page