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
Browse JSON API in a HTML interface.

Falcon API Browse This project provides a middleware for Falcon Web Framework that will render the response in an HTML form for documentation purpose.

Abhilash Raj 4 Mar 16, 2022
Cbpa - Coinbase Pro Automation for buying your favourite cryptocurrencies

cbpa Coinbase Pro Automation for making buy orders from a default bank account.

Anthony Corletti 3 Nov 27, 2022
High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (w/ Redis and PostgreSQL).

fastapi-gino-arq-uvicorn High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (powered by Redis & PostgreSQL). Contents Get Star

Leo Sussan 351 Jan 04, 2023
API using python and Fastapi framework

Welcome 👋 CFCApi is a API DEVELOPMENT PROJECT UNDER CODE FOR COMMUNITY ! Project Walkthrough 🚀 CFCApi run on Python using FASTapi Framework Docs The

Abhishek kushwaha 7 Jan 02, 2023
Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks

Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks. It provides a fully self-contained docker image that is easy to orchestrate, m

Redowan Delowar 96 Jan 02, 2023
Code Specialist 27 Oct 16, 2022
FastAPI Skeleton App to serve machine learning models production-ready.

FastAPI Model Server Skeleton Serving machine learning models production-ready, fast, easy and secure powered by the great FastAPI by Sebastián Ramíre

268 Jan 01, 2023
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
A FastAPI Plug-In to support authentication authorization using the Microsoft Authentication Library (MSAL)

FastAPI/MSAL - MSAL (Microsoft Authentication Library) plugin for FastAPI FastAPI - https://github.com/tiangolo/fastapi FastAPI is a modern, fast (hig

Dudi Levy 15 Jul 20, 2022
Prometheus exporter for several chia node statistics

prometheus-chia-exporter Prometheus exporter for several chia node statistics It's assumed that the full node, the harvester and the wallet run on the

30 Sep 19, 2022
Deploy/View images to database sqlite with fastapi

Deploy/View images to database sqlite with fastapi cd realistic Dependencies dat

Fredh Macau 1 Jan 04, 2022
Keycloack plugin for FastApi.

FastAPI Keycloack Keycloack plugin for FastApi. Your aplication receives the claims decoded from the access token. Usage Run keycloak on port 8080 and

Elber 4 Jun 24, 2022
A minimum reproducible repository for embedding panel in FastAPI

FastAPI-Panel A minimum reproducible repository for embedding panel in FastAPI Follow either This Tutorial or These steps below ↓↓↓ Clone the reposito

Tyler Houssian 15 Sep 22, 2022
Town / City geolocations with FastAPI & Mongo

geolocations-api United Kingdom Town / City geolocations with FastAPI & Mongo Build container To build a custom image or extend the api run the follow

Joe Gasewicz 3 Jan 26, 2022
🔀⏳ Easy throttling with asyncio support

Throttler Zero-dependency Python package for easy throttling with asyncio support. 📝 Table of Contents 🎒 Install 🛠 Usage Examples Throttler and Thr

Ramzan Bekbulatov 80 Dec 07, 2022
FastAPI client generator

FastAPI-based API Client Generator Generate a mypy- and IDE-friendly API client from an OpenAPI spec. Sync and async interfaces are both available Com

David Montague 283 Jan 04, 2023
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
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
Opinionated authorization package for FastAPI

FastAPI Authorization Installation pip install fastapi-authorization Usage Currently, there are two models available: RBAC: Role-based Access Control

Marcelo Trylesinski 18 Jul 04, 2022
✨️🐍 SPARQL endpoint built with RDFLib to serve machine learning models, or any other logic implemented in Python

✨ SPARQL endpoint for RDFLib rdflib-endpoint is a SPARQL endpoint based on a RDFLib Graph to easily serve machine learning models, or any other logic

Vincent Emonet 27 Dec 19, 2022