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
京东图片点击验证码识别

京东图片验证码识别 本项目是@yqchilde 大佬的 JDMemberCloseAccount 识别图形验证码(#45)思路验证,若你也有思路可以提交Issue和PR也可以在 @yqchilde 的 TG群 找到我 声明 本脚本只是为了学习研究使用 本脚本除了采集处理验证码图片没有其他任何功能,也

AntonVanke 37 Dec 22, 2022
Fetching Cryptocurrency Prices from Coingecko and Displaying them on Grafana

cryptocurrency-prices-grafana Fetching Cryptocurrency Prices from Coingecko and Displaying them on Grafana About This stack consists of: Prometheus (t

Ruan Bekker 7 Aug 01, 2022
Hyperlinks for pydantic models

Hyperlinks for pydantic models In a typical web application relationships between resources are modeled by primary and foreign keys in a database (int

Jaakko Moisio 10 Apr 18, 2022
Farlimit - FastAPI rate limit with python

FastAPIRateLimit Contributing is F&E (free&easy) Y Usage pip install farlimit N

omid 27 Oct 06, 2022
Generate Class & Decorators for your FastAPI project ✨🚀

Classes and Decorators to use FastAPI with class based routing. In particular this allows you to construct an instance of a class and have methods of that instance be route handlers for FastAPI & Pyt

Yasser Tahiri 34 Oct 27, 2022
Keepalive - Discord Bot to keep threads from expiring

keepalive Discord Bot to keep threads from expiring Installation Create a new Di

Francesco Pierfederici 5 Mar 14, 2022
Signalling for FastAPI.

fastapi-signals Signalling for FastAPI.

Henshal B 7 May 04, 2022
Sample project showing reliable data ingestion application using FastAPI and dramatiq

Create and deploy a reliable data ingestion service with FastAPI, SQLModel and Dramatiq This is the source code for the data ingestion service explain

François Voron 31 Nov 30, 2022
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 08, 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
A minimal Streamlit app showing how to launch and stop a FastAPI process on demand

Simple Streamlit + FastAPI Integration A minimal Streamlit app showing how to launch and stop a FastAPI process on demand. The FastAPI /run route simu

Arvindra 18 Jan 02, 2023
FastAPI-PostgreSQL-Celery-RabbitMQ-Redis bakcend with Docker containerization

FastAPI - PostgreSQL - Celery - Rabbitmq backend This source code implements the following architecture: All the required database endpoints are imple

Juan Esteban Aristizabal 54 Nov 26, 2022
REST API with FastAPI and JSON file.

FastAPI RESTAPI with a JSON py 3.10 First, to install all dependencies, in ./src/: python -m pip install -r requirements.txt Second, into the ./src/

Luis Quiñones Requelme 1 Dec 15, 2021
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
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
FastAPI native extension, easy and simple JWT auth

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

Konstantin Chernyshev 19 Dec 12, 2022
A basic JSON-RPC implementation for your Flask-powered sites

Flask JSON-RPC A basic JSON-RPC implementation for your Flask-powered sites. Some reasons you might want to use: Simple, powerful, flexible and python

Cenobit Technologies 273 Dec 01, 2022
This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

0 Sep 24, 2022
CLI and Streamlit applications to create APIs from Excel data files within seconds, using FastAPI

FastAPI-Wrapper CLI & APIness Streamlit App Arvindra Sehmi, Oxford Economics Ltd. | Website | LinkedIn (Updated: 21 April, 2021) fastapi-wrapper is mo

Arvindra 49 Dec 03, 2022
REST API with FastAPI and PostgreSQL

REST API with FastAPI and PostgreSQL To have the same data in db: create table CLIENT_DATA (id SERIAL PRIMARY KEY, fullname VARCHAR(50) NOT NULL,email

Luis Quiñones Requelme 1 Nov 11, 2021