Auth for use with FastAPI

Overview

FastAPI Auth

Pluggable auth for use with FastAPI

  • Supports OAuth2 Password Flow
  • Uses JWT access and refresh tokens
  • 100% mypy and test coverage
  • Supports custom user models (both ORM and pydantic) without sacrificing any type-safety

Usage:

After installing the development dependencies, the following script should run as-is:

from typing import Optional

import sqlalchemy as sa
from fastapi import FastAPI
from pydantic import EmailStr

from fastapi_auth.auth_app import BaseAuthRouterBuilder
from fastapi_auth.auth_settings import get_auth_settings
from fastapi_auth.fastapi_util.api_model import APIModel
from fastapi_auth.fastapi_util.orm.base import Base
from fastapi_auth.models.user import (
    UserBaseInDB as BaseUserModel,
    UserCreate as BaseUserCreate,
    UserCreateRequest as BaseUserCreateRequest,
    UserInDB as BaseUserInDB,
    UserUpdate as BaseUserUpdate,
)
from fastapi_auth.orm.user import BaseUser


# Pydantic Models
class ExtraUserAttributes(APIModel):
    email: Optional[EmailStr]


class UserCreate(BaseUserCreate, ExtraUserAttributes):
    pass


class UserCreateRequest(BaseUserCreateRequest, ExtraUserAttributes):
    pass


class UserInDB(BaseUserInDB, ExtraUserAttributes):
    pass


class UserUpdate(BaseUserUpdate, ExtraUserAttributes):
    pass


class UserResult(BaseUserModel, ExtraUserAttributes):
    pass


# Sqlalchemy Model
class User(BaseUser, Base):
    email = sa.Column(sa.String)


class AuthRouterBuilder(
    BaseAuthRouterBuilder[
        UserCreate, UserCreateRequest, UserInDB, UserUpdate, UserResult, User
    ]
):
    create_type = UserCreate
    create_request_type = UserCreateRequest
    in_db_type = UserInDB
    update_type = UserUpdate
    api_type = UserResult
    orm_type = User


auth_settings = get_auth_settings()
router_builder = AuthRouterBuilder(auth_settings)

app = FastAPI()

...  # Add routes

router_builder.include_auth(app.router)
router_builder.add_expired_token_cleanup(app)

print(list(app.openapi()["paths"].keys()))
"""
[
    "/auth/token",
    "/auth/token/refresh",
    "/auth/token/validate",
    "/auth/token/logout",
    "/auth/token/logout/all",
    "/auth/register",
    "/auth/self",
    "/admin/users/{user_id}",
    "/admin/users",
]
"""

You can run the above app the same way you would run any other ASGI app, and see the docs at /docs.

  • You can find a more complete example of configuring an app in tests/test_auth_app/build_app.py.
  • Dependency functions that can be used to read the user can be found in fastapi_auth.dependencies
    • If you want to inject the full user model from the database, use the classmethod AuthRouteBuilder.get_user
  • Various environment-variable-controlled settings are contained in fastapi_auth.auth_settings

Contributing:

Pull requests welcome!

To get started, clone the repo and run make develop.

Make commands:

Run make from the project root to see basic command documentation

TODO:

  • Release on PyPI (please let me know if you can help with this!)
  • Improve documentation, including a more representative example app using dependencies, etc.
  • Refactor fastapi_auth.fastapi_utils into a stand-alone package
  • Consider replacing the use of sqlalchemy's ORM with encode/databases
Owner
David Montague
David Montague
Backend Skeleton using FastAPI and Sqlalchemy ORM

Backend API Skeleton Based on @tiangolo's full stack postgres template, with some things added, some things removed, and some things changed. This is

David Montague 18 Oct 31, 2022
🤪 FastAPI + Vue构建的Mall项目后台管理

Mall项目后台管理 前段时间学习Vue写了一个移动端项目 https://www.charmcode.cn/app/mall/home 然后教程到此就结束了, 我就总感觉少点什么,计划自己着手写一套后台管理。 相关项目 移动端Mall项目源码(Vue构建): https://github.com/

王小右 131 Jan 01, 2023
FastAPI on Google Cloud Run

cloudrun-fastapi Boilerplate for running FastAPI on Google Cloud Run with Google Cloud Build for deployment. For all documentation visit the docs fold

Anthony Corletti 139 Dec 27, 2022
Backend, modern REST API for obtaining match and odds data crawled from multiple sites. Using FastAPI, MongoDB as database, Motor as async MongoDB client, Scrapy as crawler and Docker.

Introduction Apiestas is a project composed of a backend powered by the awesome framework FastAPI and a crawler powered by Scrapy. This project has fo

Fran Lozano 54 Dec 13, 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 565 Jan 02, 2023
A Python pickling decompiler and static analyzer

Fickling Fickling is a decompiler, static analyzer, and bytecode rewriter for Python pickle object serializations. Pickled Python objects are in fact

Trail of Bits 162 Dec 13, 2022
[rewrite 중] 코로나바이러스감염증-19(COVID-19)의 국내/국외 발생 동향 조회 API | Coronavirus Infectious Disease-19 (COVID-19) outbreak trend inquiry API

COVID-19API 코로나 바이러스 감염증-19(COVID-19, SARS-CoV-2)의 국내/외 발생 동향 조회 API Corona Virus Infectious Disease-19 (COVID-19, SARS-CoV-2) outbreak trend inquiry

Euiseo Cha 28 Oct 29, 2022
JSON-RPC server based on fastapi

Description JSON-RPC server based on fastapi: https://fastapi.tiangolo.com Motivation Autogenerated OpenAPI and Swagger (thanks to fastapi) for JSON-R

199 Dec 30, 2022
A simple api written in python/fastapi that serves movies from a cassandra table.

A simple api written in python/fastapi that serves movies from a cassandra table. 1)clone the repo 2)rename sample_global_config_.py to global_config.

Sreeraj 1 Aug 26, 2021
基于Pytorch的脚手架项目,Celery+FastAPI+Gunicorn+Nginx+Supervisor实现服务部署,支持Docker发布

cookiecutter-pytorch-fastapi 基于Pytorch的 脚手架项目 按规范添加推理函数即可实现Celery+FastAPI+Gunicorn+Nginx+Supervisor+Docker的快速部署 Requirements Python = 3.6 with pip in

17 Dec 23, 2022
FastAPI Boilerplate

FastAPI Boilerplate Features SQlAlchemy session Custom user class Top-level dependency Dependencies for specific permissions Celery SQLAlchemy for asy

Hide 417 Jan 07, 2023
A Jupyter server based on FastAPI (Experimental)

jupyverse is experimental and should not be used in place of jupyter-server, which is the official Jupyter server.

Jupyter Server 122 Dec 27, 2022
All of the ad-hoc things you're doing to manage incidents today, done for you, and much more!

About What's Dispatch? Put simply, Dispatch is: All of the ad-hoc things you’re doing to manage incidents today, done for you, and a bunch of other th

Netflix, Inc. 3.7k Jan 05, 2023
Money Transaction is a system based on the recent famous FastAPI.

moneyTransfer Overview Money Transaction is a system based on the recent famous FastAPI. techniques selection System's technique selection is as follo

2 Apr 28, 2021
MLServer

MLServer An open source inference server to serve your machine learning models. ⚠️ This is a Work in Progress. Overview MLServer aims to provide an ea

Seldon 341 Jan 03, 2023
更新 2.0 版本,使用 Python WEB 高性能异步框架 FastAPI 制作的抖音无水印解析下载,采用前后端分离思想!

前言 这个是 2.0 版本,使用现在流行的前后端分离思想重构。 体验网址:https://douyin.bigdataboy.cn 更新日志 2020.05.30:使用 FastAPI 前后端分离重构 2020.05.02:已更新,正常使用 2020.04.27:抖音结构更新,已修复视频有水印。(失

64 Nov 25, 2022
Online Repo Browser

MSYS2 Web Interface A simple web interface for browsing the MSYS2 repos. Rebuild CSS/JS (optional): cd frontend npm install npm run build Run for Dev

MSYS2 64 Dec 30, 2022
The template for building scalable web APIs based on FastAPI, Tortoise ORM and other.

FastAPI and Tortoise ORM. Powerful but simple template for web APIs w/ FastAPI (as web framework) and Tortoise-ORM (for working via database without h

prostomarkeloff 95 Jan 08, 2023
Example of integrating Poetry with Docker leveraging multi-stage builds.

Poetry managed Python FastAPI application with Docker multi-stage builds This repo serves as a minimal reference on setting up docker multi-stage buil

Michael Oliver 266 Dec 27, 2022
Social Distancing Detector using deep learning and capable to run on edge AI devices such as NVIDIA Jetson, Google Coral, and more.

Smart Social Distancing Smart Social Distancing Introduction Getting Started Prerequisites Usage Processor Optional Parameters Configuring AWS credent

Neuralet 129 Dec 12, 2022