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
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
Lightning FastAPI

Lightning FastAPI Lightning FastAPI framework, provides boiler plates for FastAPI based on Django Framework Explaination / | │ manage.py │ README.

Rajesh Joshi 1 Oct 15, 2021
Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker.

FastAPI + SQLModel + Alembic Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker. Want to learn how to build th

228 Jan 02, 2023
A comprehensive CRUD API generator for SQLALchemy.

FastAPI Quick CRUD Introduction Advantage Constraint Getting started Installation Usage Design Path Parameter Query Parameter Request Body Upsert Intr

192 Jan 06, 2023
Voucher FastAPI

Voucher-API Requirement Docker Installed on system Libraries Pandas Psycopg2 FastAPI PyArrow Pydantic Uvicorn How to run Download the repo on your sys

Hassan Munir 1 Jan 26, 2022
Repository for the Demo of using DVC with PyCaret & MLOps (DVC Office Hours - 20th Jan, 2022)

Using DVC with PyCaret & FastAPI (Demo) This repo contains all the resources for my demo explaining how to use DVC along with other interesting tools

Tezan Sahu 6 Jul 22, 2022
Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as a REST API Endpoint.

Jupter Notebook REST API Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as

Invictify 54 Nov 04, 2022
Redis-based rate-limiting for FastAPI

Redis-based rate-limiting for FastAPI

Glib 6 Nov 14, 2022
Generate modern Python clients from OpenAPI

openapi-python-client Generate modern Python clients from OpenAPI 3.x documents. This generator does not support OpenAPI 2.x FKA Swagger. If you need

Triax Technologies 558 Jan 07, 2023
Ready-to-use and customizable users management for FastAPI

FastAPI Users Ready-to-use and customizable users management for FastAPI Documentation: https://fastapi-users.github.io/fastapi-users/ Source Code: ht

FastAPI Users 2.3k Dec 30, 2022
🐍Pywork is a Yeoman generator to scaffold a Bare-bone Python Application

Pywork python app yeoman generator Yeoman | Npm Pywork | Home PyWork is a Yeoman generator for a basic python-worker project that makes use of Pipenv,

Vu Tran 10 Dec 16, 2022
Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

Michael Freeborn 465 Jan 07, 2023
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
Fastapi-ml-template - Fastapi ml template with python

FastAPI ML Template Run Web API Local $ sh run.sh # poetry run uvicorn app.mai

Yuki Okuda 29 Nov 20, 2022
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
REST API with FastAPI and JSON file.

FastAPI RESTAPI with a JSON py 3.10 First, to install all dependencies, in ./src/: python -m pip install -r requirements.txt Second, into the ./src/

Luis Quiñones Requelme 1 Dec 15, 2021
Dead-simple mailer micro-service for static websites

Mailer Dead-simple mailer micro-service for static websites A free and open-source software alternative to contact form services such as FormSpree, to

Romain Clement 42 Dec 21, 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
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.3k Dec 31, 2022
This repository contains learning resources for Python Fast API Framework and Docker

This repository contains learning resources for Python Fast API Framework and Docker, Build High Performing Apps With Python BootCamp by Lux Academy and Data Science East Africa.

Harun Mbaabu Mwenda 23 Nov 20, 2022