Fastapi-auth-middleware - Lightweight auth middleware for FastAPI that just works. Fits most auth workflows with only a few lines of code

Overview

FastAPI Auth Middleware

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

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://code-specialist.github.io/fastapi-auth-middleware/examples

Comments
  • tests multiple python versions in test pipeline

    tests multiple python versions in test pipeline

    This PR:

    • runs the test pipeline with all supported python versions instead of only Python 3.8
    • adds a badge for the test status on master to the README
    enhancement 
    opened by JonasScholl 2
  • proper error handling in authentication middleware

    proper error handling in authentication middleware

    When an error in an starlette AuthenticationBackend occurs, a AuthenticationError must be raised, other exceptions may produce errors like: 'RuntimeError: Caught handled exception, but response already started.' (see starlette documentation)

    This PR:

    • catches all exceptions that occur in the verify_authorization_header callback and convert them into an AuthenticationError
    • adds an optional error handler callback for specifically catching auth errors and returning a custom response (since this is already offered by the AuthenticationBackend implentation from starlette)
    • does some type hint improvements, I couldn't resist 😂
    opened by JonasScholl 1
  • OAuth2Middleware with automatic renewal added

    OAuth2Middleware with automatic renewal added

    • Async support for the AuthMiddleware
    • OAuth2Middleware added
    • Write tests (100% coverage)
    • Documentation
    • Add example

    TODO before merging:

    • Add example with the fastapi-keycloak package -> Convert to issue #1
    enhancement 
    opened by yannicschroeer 1
  • Integrate with fastapi openapi authentication

    Integrate with fastapi openapi authentication

    Is there a way to make this middleware correctly integrate with the openapi generators from fastapi? For instance. Currently, this:

    @router.get("/me", response_model=schemas.User)
    @requires('user')
    async def read_user_me(request: Request, db: Session = Depends(get_db)):
      user = User.get_user(db, request.user.userid)
      return user
    

    Is not detected by fastapi's openapi generator as an authenticated endpoint. Is there a way to make this library integrate correctly with the openapi generator.

    image

    opened by xtrm0 0
  • Protected and Unprotected Endpoints

    Protected and Unprotected Endpoints

    I'm trying the middleware and reading the docs

    Once Starlette includes this and FastAPI adopts it, there will be a more elegant solution to this.

    FYI https://github.com/encode/starlette/pull/1649

    opened by paolodina 0
Releases(1.0.2)
  • 1.0.2(Apr 7, 2022)

  • 1.0.1(Mar 24, 2022)

    What's Changed

    • Excluded URLs by @yannicschroeer in https://github.com/code-specialist/fastapi-auth-middleware/pull/6

    Full Changelog: https://github.com/code-specialist/fastapi-auth-middleware/compare/1.0.0...1.0.1

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Mar 15, 2022)

    What's Changed

    • proper error handling in authentication middleware by @JonasScholl in https://github.com/code-specialist/fastapi-auth-middleware/pull/2
    • OAuth2Middleware with automatic renewal added by @yannicschroeer in https://github.com/code-specialist/fastapi-auth-middleware/pull/1
    • Improved the reusability of the middleware by passing all headers ins… by @yannicschroeer in https://github.com/code-specialist/fastapi-auth-middleware/pull/3

    New Contributors

    • @JonasScholl made their first contribution in https://github.com/code-specialist/fastapi-auth-middleware/pull/2
    • @yannicschroeer made their first contribution in https://github.com/code-specialist/fastapi-auth-middleware/pull/1

    Full Changelog: https://github.com/code-specialist/fastapi-auth-middleware/commits/1.0.0

    Source code(tar.gz)
    Source code(zip)
Owner
Code Specialist
Code Quality Blog about simplifying concepts and making life easier for developers
Code Specialist
Cookiecutter template for FastAPI projects using: Machine Learning, Poetry, Azure Pipelines and Pytests

cookiecutter-fastapi In order to create a template to FastAPI projects. 🚀 Important To use this project you don't need fork it. Just run cookiecutter

Arthur Henrique 225 Dec 28, 2022
A dynamic FastAPI router that automatically creates CRUD routes for your models

⚡ Create CRUD routes with lighting speed ⚡ A dynamic FastAPI router that automatically creates CRUD routes for your models

Adam Watkins 950 Jan 08, 2023
Fastapi performans monitoring

Fastapi-performans-monitoring This project is a simple performance monitoring for FastAPI. License This project is licensed under the terms of the MIT

bilal alpaslan 11 Dec 31, 2022
FastAPI CRUD template using Deta Base

Deta Base FastAPI CRUD FastAPI CRUD template using Deta Base Setup Install the requirements for the CRUD: pip3 install -r requirements.txt Add your D

Sebastian Ponce 2 Dec 15, 2021
Slack webhooks API served by FastAPI

Slackers Slack webhooks API served by FastAPI What is Slackers Slackers is a FastAPI implementation to handle Slack interactions and events. It serves

Niels van Huijstee 68 Jan 05, 2023
API for Submarino store

submarino-api API for the submarino e-commerce documentation read the documentation in: https://submarino-api.herokuapp.com/docs or in https://submari

Miguel 1 Oct 14, 2021
FastAPI + PeeWee = <3

FastAPIwee FastAPI + PeeWee = 3 Using Python = 3.6 🐍 Installation pip install FastAPIwee 🎉 Documentation Documentation can be found here: https://

16 Aug 30, 2022
MS Graph API authentication example with Fast API

MS Graph API authentication example with Fast API What it is & does This is a simple python service/webapp, using FastAPI with server side rendering,

Andrew Hart 4 Aug 11, 2022
flask extension for integration with the awesome pydantic package

flask extension for integration with the awesome pydantic package

249 Jan 06, 2023
fastapi-mqtt is extension for MQTT protocol

fastapi-mqtt MQTT is a lightweight publish/subscribe messaging protocol designed for M2M (machine to machine) telemetry in low bandwidth environments.

Sabuhi 144 Dec 28, 2022
FastAPI with Docker and Traefik

Dockerizing FastAPI with Postgres, Uvicorn, and Traefik Want to learn how to build this? Check out the post. Want to use this project? Development Bui

51 Jan 06, 2023
Flask-vs-FastAPI - Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks.

Flask-vs-FastAPI Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks. IntroductionIn Flask is a popular mic

Mithlesh Navlakhe 1 Jan 01, 2022
Instrument your FastAPI app

Prometheus FastAPI Instrumentator A configurable and modular Prometheus Instrumentator for your FastAPI. Install prometheus-fastapi-instrumentator fro

Tim Schwenke 441 Jan 05, 2023
Deploy/View images to database sqlite with fastapi

Deploy/View images to database sqlite with fastapi cd realistic Dependencies dat

Fredh Macau 1 Jan 04, 2022
A kedro-plugin to serve Kedro Pipelines as API

General informations Software repository Latest release Total downloads Pypi Code health Branch Tests Coverage Links Documentation Deployment Activity

Yolan Honoré-Rougé 12 Jul 15, 2022
Cookiecutter API for creating Custom Skills for Azure Search using Python and Docker

cookiecutter-spacy-fastapi Python cookiecutter API for quick deployments of spaCy models with FastAPI Azure Search The API interface is compatible wit

Microsoft 379 Jan 03, 2023
Fast, simple API for Apple firmwares.

Loyal Fast, Simple API for fetching Apple Firmwares. The API server is closed due to some reasons. Wait for v2 releases. Features Fetching Signed IPSW

11 Oct 28, 2022
Simple FastAPI Example : Blog API using FastAPI : Beginner Friendly

fastapi_blog FastAPI : Simple Blog API with CRUD operation Steps to run the project: git clone https://github.com/mrAvi07/fastapi_blog.git cd fastapi-

Avinash Alanjkar 1 Oct 08, 2022
This project shows how to serve an ONNX-optimized image classification model as a web service with FastAPI, Docker, and Kubernetes.

Deploying ML models with FastAPI, Docker, and Kubernetes By: Sayak Paul and Chansung Park This project shows how to serve an ONNX-optimized image clas

Sayak Paul 104 Dec 23, 2022
Minecraft biome tile server writing on Python using FastAPI

Blocktile Minecraft biome tile server writing on Python using FastAPI Usage https://blocktile.herokuapp.com/overworld/{seed}/{zoom}/{col}/{row}.png s

Vladimir 2 Aug 31, 2022