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 native extension, easy and simple JWT auth

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

Konstantin Chernyshev 19 Dec 12, 2022
FastAPI Auth Starter Project

This is a template for FastAPI that comes with authentication preconfigured.

Oluwaseyifunmi Oyefeso 6 Nov 13, 2022
Starlette middleware for Prerender

Prerender Python Starlette Starlette middleware for Prerender Documentation: https://BeeMyDesk.github.io/prerender-python-starlette/ Source Code: http

BeeMyDesk 14 May 2, 2021
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

Tomasz Wójcik 300 Dec 26, 2022
Starlette middleware for Prerender

Prerender Python Starlette Starlette middleware for Prerender Documentation: https://BeeMyDesk.github.io/prerender-python-starlette/ Source Code: http

BeeMyDesk 13 Jul 27, 2020
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

Tomasz Wójcik 110 Feb 16, 2021
Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡

csrf-starlette-fastapi Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡ Will work with either a <input type="hidden"> field or ajax

Nathaniel Sabanski 9 Nov 20, 2022
:rocket: CLI tool for FastAPI. Generating new FastAPI projects & boilerplates made easy.

Project generator and manager for FastAPI. Source Code: View it on Github Features ?? Creates customizable project boilerplate. Creates customizable a

Yagiz Degirmenci 1k Jan 2, 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 8, 2022
Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI

FastAPI Ariadne Example Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI - GitHub ###Запуск на локальном окру

ZeBrains Team 9 Nov 10, 2022
Sample-fastapi - A sample app using Fastapi that you can deploy on App Platform

Getting Started We provide a sample app using Fastapi that you can deploy on App

Erhan BÜTE 2 Jan 17, 2022
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 1, 2022
FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management

FastAPI Server-sided Session FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management.

DevGuyAhnaf 5 Dec 23, 2022
fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability

FastAPI2 Admin Introduction fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability. Now

Glib 14 Dec 5, 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
FastAPI-Amis-Admin is a high-performance, efficient and easily extensible FastAPI admin framework. Inspired by django-admin, and has as many powerful functions as django-admin.

简体中文 | English 项目介绍 FastAPI-Amis-Admin fastapi-amis-admin是一个拥有高性能,高效率,易拓展的fastapi管理后台框架. 启发自Django-Admin,并且拥有不逊色于Django-Admin的强大功能. 源码 · 在线演示 · 文档 · 文

AmisAdmin 318 Dec 31, 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 4, 2022
This code generator creates FastAPI app from an openapi file.

fastapi-code-generator This code generator creates FastAPI app from an openapi file. This project is an experimental phase. fastapi-code-generator use

Koudai Aono 632 Jan 5, 2023
Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ⭐

FRDP Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ⛏ . Getting Started Fe

BnademOverflow 53 Dec 29, 2022