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
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
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 04, 2023
Example of using FastAPI and MongoDB database.

FastAPI Todo Application Example of using FastAPI and MangoDB database. 💡 Prerequisites Python ⚙️ Build & Run The first thing to do is to clone the r

Bobynets Ivan 1 Oct 29, 2021
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
An image validator using FastAPI.

fast_api_image_validator An image validator using FastAPI.

Kevin Zehnder 7 Jan 06, 2022
FastAPI framework plugins

Plugins for FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi-plugins FastAPI framework plugins Cache Mem

RES 239 Dec 28, 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
OpenAPI generated FastAPI server

OpenAPI generated FastAPI server This Python package is automatically generated by the OpenAPI Generator project: API version: 1.0.0 Build package: or

microbo 1 Oct 31, 2021
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
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 simple web to serve data table. It is built with Vuetify, Vue, FastApi.

simple-report-data-table-vuetify A simple web to serve data table. It is built with Vuetify, Vue, FastApi. The main features: RBAC with casbin simple

11 Dec 22, 2022
REST API with FastAPI and SQLite3.

REST API with FastAPI and SQLite3

Luis Quiñones Requelme 2 Mar 14, 2022
🤪 FastAPI + Vue构建的Mall项目后台管理

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

王小右 131 Jan 01, 2023
[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
Recommend recipes based on what ingredients you have at home

🌱 MyChef 📦 Overview MyChef is an application that helps you decide what meal to make based on what you have at home. Simply enter in ingredients you

Logan Connolly 44 Nov 08, 2022
FastAPI构建的API服务

使用FastAPI 构建的商城项目API 学习FastAPI 构建项目目录 构建项目接口: 对应博客:https://www.charmcode.cn/article/2020-06-08_vue_mall_api 声明 此项目已经不再维护, 可以参考我另外一个项目https://github.co

王小右 64 Oct 04, 2022
官方文档已经有翻译的人在做了,

FastAPI 框架,高性能,易学,快速编码,随时可供生产 文档:https://fastapi.tiangolo.com 源码:https://github.com/tiangolo/fastapi FastAPI 是一个现代、快速(高性能)的 Web 框架,基于标准 Python 类型提示,使用

ApacheCN 27 Nov 11, 2022
FastAPI Learning Example,对应中文视频学习教程:https://space.bilibili.com/396891097

视频教学地址 中文学习教程 1、本教程每一个案例都可以独立跑,前提是安装好依赖包。 2、本教程并未按照官方教程顺序,而是按照实际使用顺序编排。 Video Teaching Address FastAPI Learning Example 1.Each case in this tutorial c

381 Dec 11, 2022
EML analyzer is an application to analyze the EML file

EML analyzer EML analyzer is an application to analyze the EML file which can: Analyze headers. Analyze bodies. Extract IOCs (URLs, domains, IP addres

Manabu Niseki 162 Dec 28, 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