Skip to main content

FastAPI Authorization Gateway

Python package CI PyPI - Version

This library enables route-level authorization for FastAPI apps. It is particularly useful in cases where you need to limit access to routes that you do not directly control. For example, if you make use of a library which sets up a range of routes on your behalf (it was designed with stac-fastapi in mind), you can use this library to restrict access to any of those routes using authorization policies. These policies can be evaluated against a combination of route paths, methods, path parameters and query parameters. It also provides a mechanism for mutating requests before passing them on to downstream endpoints, for cases where you need to pre-emptively filter a request.

Setup

Install via pip

python -m pip install fastapi-authorization-gateway

# or from source
python -m pip install git+https://github.com/developmentseed/fastapi-authorization-gateway.git`

Usage

If you are just starting out and want an end-to-end explanation of how this library works and how to integrate it into your app, please check out the Tutorial.

If you are looking for a recipe to solve a specific issue, please check out the How To.

Quickstart

If you don't want the full tutorial and just want to plug this right into your app with minimal explanation, you can use the code snippet below.

from fastapi import Depends, Request
from typing import Annotated, Optional
from fastapi_authorization_gateway.auth import build_authorization_dependency
from fastapi_authorization_gateway.types import Policy, RoutePermission


async def get_user(request: Request):
    """
    Replace this with a function to retrieve a real user
    (from a token, for example).
    """
    return {
        "username": "test"
    }


async def policy_generator(request: Request, user: Annotated[dict, Depends(get_user)]) -> Policy:
    """
    Define your policies here based on the requesting user or, really,
    whatever you like. This function will be injected as a dependency
    into the authorization dependency and must return a Policy.
    """

    # We will generate some policies that cover all routes for the app,
    # so we need to enumerate them here.
    all_routes: list[APIRoute] = request.app.routes

    # A permission matching write access to all routes, with no constraints
    # on path or query parameters
    all_write = RoutePermission(
        paths=[route.path_format for route in all_routes],
        methods=["POST", "PUT", "PATCH", "DELETE"],
    )

    # a permission matching read access to all routes, with no constraints
    # on path or query parameters
    all_read = RoutePermission(
        paths=[route.path_format for route in all_routes], methods=["GET"]
    )

    # read only policy allows read requests on all routes and denies write requests
    # falling back to denying a request if it matches none of the permissions
    read_only_policy = Policy(allow=[all_read], deny=[all_write], default_deny=True)

    # a more permissive policy granting write and read access on all routes, falling back
    # to approving a request if it matches none of the permissions
    authorized_policy = Policy(allow=[all_write, all_read], default_deny=False)

    if not user:
        # anonymous requests get read only permissions
        return read_only_policy
    else:
        # authenticated requests get full permissions
        return authorized_policy


# build the authorization dependency
authorization = build_authorization_dependency(
    policy_generator=policy_generator,
)


app = FastAPI(dependencies=[Depends(authorization)])


@app.get("/test")
def get_test(request: Request):
    return {"status": "ok"}


@app.post("/test")
def post_test(request: Request):
    print("Should not be able to reach this endpoint with read-only policy")
    return {"status": "ok"}

Release files for fastapi-authorization-gateway 0.0.4

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

Source distribution (sdist)

Source distribution for fastapi-authorization-gateway 0.0.4
File Size Uploaded
fastapi_authorization_gateway-0.0.4.tar.gz 9.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-authorization-gateway 0.0.4
File Interpreter ABI Platform
fastapi_authorization_gateway-0.0.4-py3-none-any.whl Python 3 none any Details

Total release size: 20.1 kB

Release files / fastapi_authorization_gateway-0.0.4.tar.gz

Download URL fastapi_authorization_gateway-0.0.4.tar.gz
Size 9.2 kB
Tags Source
SHA-256 checksum
How to use checksums
089feda199cfe91a2c0de22febfe3e40ec5e0ecf588c11ff71d840969b58b831
BLAKE2b-256 checksum
How to use checksums
77ae276abc21bec5e6fe39c7c36714511d38fb9e28dbb4ddfaa405a26fe8effb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/5.1.0 CPython/3.12.5

Release files / fastapi_authorization_gateway-0.0.4-py3-none-any.whl

Download URL fastapi_authorization_gateway-0.0.4-py3-none-any.whl
Size 10.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
93ca35edf87a367a555cf378775252ea09f3a271bcb00f1d5185050de11ee28a
BLAKE2b-256 checksum
How to use checksums
676bce6aa714d01185bdffdb6b3dd93923ea47f8cdeccf983cd18be951abb398
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/5.1.0 CPython/3.12.5

Release history Release notifications | RSS feed

This release

0.0.4 This release

2 release files

0.0.3

2 release files

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