Skip to main content

FastAPI Auth Middleware

codecov CodeFactor Py3.7 Py3.7 Py3.7 Py3.7

We at Code Specialist love FastAPI for its simplicity and feature-richness. Though we were a bit staggered by the poor documentation and integration of auth-concepts. That's why we wrote a FastAPI Auth Middleware. It integrates seamlessly into FastAPI applications and requires minimum configuration. It is built upon Starlette and thereby requires no dependencies you do not have included anyway.

Caution: This is a middleware to plug in existing authentication. Even though we offer some sample code, this package assumes you already have a way to generate and verify whatever you use, to authenticate your users. In most of the usual cases this will be an access token or bearer. For instance as in OAuth2 or Open ID Connect.

Install

pip install fastapi_auth_middleware

Documentation

More detailed docs are available at https://fastapi-auth-middleware.code-specialist.com.

Why FastAPI Auth Middlware?

  • Application or Route scoped automatic authorization and authentication with the perks of dependency injection (But without inflated signatures due to Depends())
  • Lightweight without additional dependencies
  • Easy to configure
  • Easy to extend and adjust to specific needs
  • Plug-and-Play feeling

Usage

The usage of this middleware requires you to provide a single function that validates a given authorization header. The middleware will extract the content of the Authorization HTTP header and inject it into your function that returns a list of scopes and a user object. The list of scopes may be empty if you do not use any scope based concepts. The user object must be a BaseUser or any inheriting class such as FastAPIUser. Thereby, your verify_authorization_header function must implement a signature that contains a string as an input and a Tuple of a List of strings and a BaseUser as output:

from typing import Tuple, List
from fastapi_auth_middleware import FastAPIUser
from starlette.authentication import BaseUser

...
# Takes a string that will look like 'Bearer eyJhbGc...'
def verify_authorization_header(auth_header: str) -> Tuple[List[str], BaseUser]: # Returns a Tuple of a List of scopes (string) and a BaseUser
    user = FastAPIUser(first_name="Code", last_name="Specialist", user_id=1)  # Usually you would decode the JWT here and verify its signature to extract the 'sub'
    scopes = []  # You could for instance use the scopes provided in the JWT or request them by looking up the scopes with the 'sub' somewhere
    return scopes, user

This function is then included as an keyword argument when adding the middleware to the app.

from fastapi import FastAPI
from fastapi_auth_middleware import AuthMiddleware

...

app = FastAPI()
app.add_middleware(AuthMiddleware, verify_authorization_header=verify_authorization_header)

After adding this middleware, all requests will pass the verify_authorization_header function and contain the scopes as well as the user object as injected dependencies. All requests now pass the verify_authorization_header method. You may also verify that users posses scopes with requires:

from starlette.authentication import requires

...

@app.get("/")
@requires(["admin"])  # Will result in an HTTP 401 if the scope is not matched
def some_endpoint():
    ...

You are also able to use the user object you injected on the request object:

from starlette.requests import Request

...

@app.get('/')
def home(request: Request):
    return f"Hello {request.user.first_name}"  # Assuming you use the FastAPIUser object

Examples

Various examples on how to use this middleware are available at https://fastapi-auth-middleware.code-specialist.com/examples

Metadata

Release files for fastapi_auth_middleware 1.0.2

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_auth_middleware 1.0.2
File Size Uploaded
fastapi_auth_middleware-1.0.2.tar.gz 33.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi_auth_middleware 1.0.2
File Interpreter ABI Platform
fastapi_auth_middleware-1.0.2-py3-none-any.whl Python 3 none any Details

Total release size: 46.1 kB

Release files / fastapi_auth_middleware-1.0.2.tar.gz

Download URL fastapi_auth_middleware-1.0.2.tar.gz
Size 33.9 kB
Tags Source
SHA-256 checksum
How to use checksums
e1eea9cfced9edd5dc433ee71499260a5a562cc2c258aa459b1dbb761c4120cd
BLAKE2b-256 checksum
How to use checksums
b78705ae6e523d348191cb3f529aeebb55d8ec92fd15f4f79d30a055cb1932ca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-requests/2.27.1

Release files / fastapi_auth_middleware-1.0.2-py3-none-any.whl

Download URL fastapi_auth_middleware-1.0.2-py3-none-any.whl
Size 12.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c96a9a15dcd22c3801dadb8b45f7a73070f2edabd52e0846bdfe7bcbfaae8fe7
BLAKE2b-256 checksum
How to use checksums
10636f3d4280485d5737a45f1f5065d90470efcc8a13e5ab83c287bb9149f7dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-requests/2.27.1

Release history Release notifications | RSS feed

This release

1.0.2 This release

2 release files

1.0.1

2 release files

1.0.0

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