Skip to main content

A route-based authorization framework for FastAPI

Project description

FastAPI Authorization Gateway

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. Use the github URL until we get this up on pypi:

pip install git+https://github.com/edkeeble/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"}

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

fastapi_authorization_gateway-0.0.3.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

File details

Details for the file fastapi_authorization_gateway-0.0.3.tar.gz.

File metadata

File hashes

Hashes for fastapi_authorization_gateway-0.0.3.tar.gz
Algorithm Hash digest
SHA256 8e03ef8f3f66bc354d07444efa319be4cbed8a024d216287ab659c47af040bee
MD5 285f1d76f09cc644c1fa81605453a496
BLAKE2b-256 2523c6a611fbeeedc611d4dd40f34a422e91e22f9394eb2e73ed51fafdb0f204

See more details on using hashes here.

File details

Details for the file fastapi_authorization_gateway-0.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_authorization_gateway-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 eff255db4c789a5c27e5a4e738b4cf8c8299b1a65ce94e5ab904962dc5f2ee6e
MD5 2a4e62346855bc1df8d762f2cf2c7d88
BLAKE2b-256 63e0ab72254f61fb32935d9525a18b823c73aec61471a7ca76ff90497a3f539b

See more details on using hashes here.

Supported by

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