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
Single Page App with Flask and Vue.js

Developing a Single Page App with FastAPI and Vue.js Want to learn how to build this? Check out the post. Want to use this project? Build the images a

91 Jan 05, 2023
Browse JSON API in a HTML interface.

Falcon API Browse This project provides a middleware for Falcon Web Framework that will render the response in an HTML form for documentation purpose.

Abhilash Raj 4 Mar 16, 2022
A request rate limiter for fastapi

fastapi-limiter Introduction FastAPI-Limiter is a rate limiting tool for fastapi routes. Requirements redis Install Just install from pypi pip insta

long2ice 200 Jan 08, 2023
Redis-based rate-limiting for FastAPI

Redis-based rate-limiting for FastAPI

Glib 6 Nov 14, 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 Documentation: https://fast

Adam Watkins 943 Jan 01, 2023
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.

Full Stack FastAPI and PostgreSQL - Base Project Generator Generate a backend and frontend stack using Python, including interactive API documentation

Sebastián Ramírez 10.8k Jan 08, 2023
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
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 562 Jan 01, 2023
🔀⏳ Easy throttling with asyncio support

Throttler Zero-dependency Python package for easy throttling with asyncio support. 📝 Table of Contents 🎒 Install 🛠 Usage Examples Throttler and Thr

Ramzan Bekbulatov 80 Dec 07, 2022
FastAPI native extension, easy and simple JWT auth

fastapi-jwt FastAPI native extension, easy and simple JWT auth

Konstantin Chernyshev 19 Dec 12, 2022
CLI and Streamlit applications to create APIs from Excel data files within seconds, using FastAPI

FastAPI-Wrapper CLI & APIness Streamlit App Arvindra Sehmi, Oxford Economics Ltd. | Website | LinkedIn (Updated: 21 April, 2021) fastapi-wrapper is mo

Arvindra 49 Dec 03, 2022
OpenAPI for Todolist RESTful API

swagger-client OpenAPI for Todolist RESTful API This Python package is automatically generated by the Swagger Codegen project: API version: 1 Package

Iko Afianando 1 Dec 19, 2021
Opentracing support for Starlette and FastApi

Starlette-OpenTracing OpenTracing support for Starlette and FastApi. Inspired by: Flask-OpenTracing OpenTracing implementations exist for major distri

Rene Dohmen 63 Dec 30, 2022
Simple web app example serving a PyTorch model using streamlit and FastAPI

streamlit-fastapi-model-serving Simple example of usage of streamlit and FastAPI for ML model serving described on this blogpost and PyConES 2020 vide

Davide Fiocco 291 Jan 06, 2023
Toolkit for developing and maintaining ML models

modelkit Python framework for production ML systems. modelkit is a minimalist yet powerful MLOps library for Python, built for people who want to depl

140 Dec 27, 2022
API Simples com python utilizando a biblioteca FastApi

api-fastapi-python API Simples com python utilizando a biblioteca FastApi Para rodar esse script são necessárias duas bibliotecas: Fastapi: Comando de

Leonardo Grava 0 Apr 29, 2022
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python Examples. The beyonic APIs Doc Reference: https://apidocs.beyonic.com/ To start using the Beyonic API Python API, you need to start

Harun Mbaabu Mwenda 46 Sep 01, 2022
京东图片点击验证码识别

京东图片验证码识别 本项目是@yqchilde 大佬的 JDMemberCloseAccount 识别图形验证码(#45)思路验证,若你也有思路可以提交Issue和PR也可以在 @yqchilde 的 TG群 找到我 声明 本脚本只是为了学习研究使用 本脚本除了采集处理验证码图片没有其他任何功能,也

AntonVanke 37 Dec 22, 2022
A FastAPI WebSocket application that makes use of ncellapp package by @hemantapkh

ncellFastAPI author: @awebisam Used FastAPI to create WS application. Ncellapp module by @hemantapkh NOTE: Not following best practices and, needs ref

Aashish Bhandari 7 Oct 01, 2021
Get MODBUS data from Sofar (K-TLX) inverter through LSW-3 or LSE module

SOFAR Inverter + LSW-3/LSE Small utility to read data from SOFAR K-TLX inverters through the Solarman (LSW-3/LSE) datalogger. Two scripts to get inver

58 Dec 29, 2022