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
SuperSaaSFastAPI - Python SaaS Boilerplate for building Software-as-Service (SAAS) apps with FastAPI, Vue.js & Tailwind

Python SaaS Boilerplate for building Software-as-Service (SAAS) apps with FastAP

Rudy Bekker 31 Jan 10, 2023
Complete Fundamental to Expert Codes of FastAPI for creating API's

FastAPI FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3 based on standard Python type hints. The key featu

Pranav Anand 1 Nov 28, 2021
🍃 A comprehensive monitoring and alerting solution for the status of your Chia farmer and harvesters.

chia-monitor A monitoring tool to collect all important metrics from your Chia farming node and connected harvesters. It can send you push notificatio

Philipp Normann 153 Oct 21, 2022
Prometheus integration for Starlette.

Starlette Prometheus Introduction Prometheus integration for Starlette. Requirements Python 3.6+ Starlette 0.9+ Installation $ pip install starlette-p

José Antonio Perdiguero 229 Dec 21, 2022
Regex Converter for Flask URL Routes

Flask-Reggie Enable Regex Routes within Flask Installation pip install flask-reggie Configuration To enable regex routes within your application from

Rhys Elsmore 48 Mar 07, 2022
A server hosts a FastAPI application and multiple clients can be connected to it via SocketIO.

FastAPI_and_SocketIO A server hosts a FastAPI application and multiple clients can be connected to it via SocketIO. Executing server.py sets up the se

Ankit Rana 2 Mar 04, 2022
An alternative implement of Imjad API | Imjad API 的开源替代

HibiAPI An alternative implement of Imjad API. Imjad API 的开源替代. 前言 由于Imjad API这是什么?使用人数过多, 致使调用超出限制, 所以本人希望提供一个开源替代来供社区进行自由的部署和使用, 从而减轻一部分该API的使用压力 优势

Mix Technology 450 Dec 29, 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

Adam Watkins 950 Jan 08, 2023
A simple Redis Streams backed Chat app using Websockets, Asyncio and FastAPI/Starlette.

redis-streams-fastapi-chat A simple demo of Redis Streams backed Chat app using Websockets, Python Asyncio and FastAPI/Starlette. Requires Python vers

ludwig404 135 Dec 19, 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 02, 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 562 Jan 01, 2023
A set of demo of deploying a Machine Learning Model in production using various methods

Machine Learning Model in Production This git is for those who have concern about serving your machine learning model to production. Overview The tuto

Vo Van Tu 53 Sep 14, 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
Turns your Python functions into microservices with web API, interactive GUI, and more.

Instantly turn your Python functions into production-ready microservices. Deploy and access your services via HTTP API or interactive UI. Seamlessly export your services into portable, shareable, and

Machine Learning Tooling 2.8k Jan 04, 2023
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
Pagination support for flask

flask-paginate Pagination support for flask framework (study from will_paginate). It supports several css frameworks. It requires Python2.6+ as string

Lix Xu 264 Nov 07, 2022
A comprehensive CRUD API generator for SQLALchemy.

FastAPI Quick CRUD Introduction Advantage Constraint Getting started Installation Usage Design Path Parameter Query Parameter Request Body Upsert Intr

192 Jan 06, 2023
cookiecutter template for web API with python

Python project template for Web API with cookiecutter What's this This provides the project template including minimum test/lint/typechecking package

Hitoshi Manabe 4 Jan 28, 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
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