FastAPI native extension, easy and simple JWT auth

Overview

fastapi-jwt

Test Publish codecov pypi

FastAPI native extension, easy and simple JWT auth


Documentation: https://k4black.github.io/fastapi-jwt/
Source Code: https://github.com/k4black/fastapi-jwt/

Installation

pip install fastapi-jwt

Usage

This library made in fastapi style, so it can be used as standard security features

from fastapi import FastAPI, Security
from fastapi_jwt import JwtAuthorizationCredentials, JwtAccessBearer


app = FastAPI()
access_security = JwtAccessBearer(secret_key="secret_key", auto_error=True)


@app.post("/auth")
def auth():
    subject = {"username": "username", "role": "user"}
    return {"access_token": access_security.create_access_token(subject=subject)}


@app.get("/users/me")
def read_current_user(
    credentials: JwtAuthorizationCredentials = Security(access_security),
):
    return {"username": credentials["username"], "role": credentials["role"]}

For more examples see usage docs

Alternatives

  • FastAPI docs suggest writing it manually, but

    • code duplication
    • opportunity for bugs
  • There is nice fastapi-jwt-auth, but

    • poorly supported
    • not "FastAPI-style" (not native functions parameters)

FastAPI Integration

There it is open and maintained Pull Request #3305 to the fastapi repo. Currently, not considered.

Requirements

  • fastapi
  • python-jose[cryptography]
Comments
  • How to refresh tokens?

    How to refresh tokens?

    I'm currently trying to implement the refresh token functionality, but I always get the error:

    Credentials are not provided
    

    The request is made using axios with withCredentials: true enabled in the options.

    Here's the code for the server:

    @router.post(
        "/refresh",
    )
    async def refresh_token(
        response: Response,
        credentials: JwtAuthorizationCredentials = Security(refresh_security),
        db: Session = Depends(get_db),
    ):
        logger.info("Request: Refresh -> New Request to refresh JWT token.")
    
        user = get_user_by_id(db, credentials["id"])
    
        logger.info("Request: Refresh -> Returning new credentials.")
    
        set_authentication_cookies(response, user)
    
        return {
            "user": user,
            "detail": "Token refreshed successfully!"
        }
    
    opened by Myzel394 6
  • Add compatibility for Python 3.10

    Add compatibility for Python 3.10

    Changes:

    1. Remove the version upper-limit for Python, fastapi, and python-jose
    2. Add Python 3.10 to the Test workflow
      • testing against 3.10 is passing

    Cheers! Kyle

    opened by smithk86 1
  • Proposal to add a custom message for expired signature and incorrect token

    Proposal to add a custom message for expired signature and incorrect token

    Hi @k4black ,

    FYI:this is just a proposal and not complete PR. If you agree, i will enrich the PR

    Proposal: I would like to propose to add custom message as a param when creating a bearer token and refresh token. i have a use case where i need to pass different languages as message.

    opened by rakesh1988 1
  • No access token type checking?

    No access token type checking?

    "credentials: JwtAuthorizationCredentials = Security(refresh_security)" allows only the refresh token. "credentials: JwtAuthorizationCredentials = Security(access_security)" allows both the access token and the refresh token. did you intend this?

    class JwtAccess(JwtAuthBase):

    def __init__(
        self,
        secret_key: str,
        places: Optional[Set[str]] = None,
        auto_error: bool = True,
        algorithm: str = jwt.ALGORITHMS.HS256,
        access_expires_delta: Optional[timedelta] = None,
        refresh_expires_delta: Optional[timedelta] = None,
    ):
        super().__init__(
            secret_key,
            places=places,
            auto_error=auto_error,
            algorithm=algorithm,
            access_expires_delta=access_expires_delta,
            refresh_expires_delta=refresh_expires_delta,
        )
    
    async def _get_credentials(
        self,
        bearer: Optional[JwtAuthBase.JwtAccessBearer],
        cookie: Optional[JwtAuthBase.JwtAccessCookie],
    ) -> Optional[JwtAuthorizationCredentials]:
        payload = await self._get_payload(bearer, cookie)
    
        if payload:
            return JwtAuthorizationCredentials(
                payload["subject"], payload.get("jti", None)
            )
        return None
    

    class JwtRefresh(JwtAuthBase):

    def __init__(
        self,
        secret_key: str,
        places: Optional[Set[str]] = None,
        auto_error: bool = True,
        algorithm: str = jwt.ALGORITHMS.HS256,
        access_expires_delta: Optional[timedelta] = None,
        refresh_expires_delta: Optional[timedelta] = None,
    ):
        super().__init__(
            secret_key,
            places=places,
            auto_error=auto_error,
            algorithm=algorithm,
            access_expires_delta=access_expires_delta,
            refresh_expires_delta=refresh_expires_delta,
        )
    
    async def _get_credentials(
        self,
        bearer: Optional[JwtAuthBase.JwtRefreshBearer],
        cookie: Optional[JwtAuthBase.JwtRefreshCookie],
    ) -> Optional[JwtAuthorizationCredentials]:
        payload = await self._get_payload(bearer, cookie)
    
        if payload is None:
            return None
    
        if "type" not in payload or payload["type"] != "refresh":
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_401_UNAUTHORIZED,
                    detail="Wrong token: 'type' is not 'refresh'",
                )
            else:
                return None
    
        return JwtAuthorizationCredentials(
            payload["subject"], payload.get("jti", None)
        )
    
    opened by ohgoodjay 0
  • Bump supported python version?

    Bump supported python version?

    Im unable to install this project in my python 3.10 project, as you have pinned >=3.7,<3.10 in setup.cfg

    I think this code will probably run with 3.10

    opened by farridav 2
  • Is this project actively maintained?

    Is this project actively maintained?

    I am looking for a fast api jwt extension that is still maintained. Looks like this repo was created to replace poorly maintained fastapi-jwt-auth but you have PRs opened for 3 months...

    opened by jmilosze 1
A FastAPI Framework for things like Database, Redis, Logging, JWT Authentication and Rate Limits

A FastAPI Framework for things like Database, Redis, Logging, JWT Authentication and Rate Limits Install You can install this Library with: pip instal

Tert0 33 Nov 28, 2022
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
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 Auth Starter Project

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

Oluwaseyifunmi Oyefeso 6 Nov 13, 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
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
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 23 Feb 11, 2021
An extension library for FastAPI framework

FastLab An extension library for FastAPI framework Features Logging Models Utils Routers Installation use pip to install the package: pip install fast

Tezign Lab 10 Jul 11, 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
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
Пример использования 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-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
Easy and secure implementation of Azure AD for your FastAPI APIs 🔒

FastAPI-Azure-auth Azure AD Authentication for FastAPI apps made easy. ?? Description FastAPI is a modern, fast (high-performance), web framework for

Intility 216 Dec 27, 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 7, 2023
FastAPI simple cache

FastAPI Cache Implements simple lightweight cache system as dependencies in FastAPI. Installation pip install fastapi-cache Usage example from fastapi

Ivan Sushkov 188 Dec 29, 2022
FastAPI simple cache

FastAPI Cache Implements simple lightweight cache system as dependencies in FastAPI. Installation pip install fastapi-cache Usage example from fastapi

Ivan Sushkov 87 Feb 12, 2021