Skip to content

FastAPI backend guide #980

@FlxMgdnz

Description

@FlxMgdnz

We've received this middleware snipped for JWT handling in Python with FastAPI.

Check the code (does it work, can it be minimized?) and add it to docs/guides/backend if you approve.

from typing import Any

import jwt
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

HANKO_API_URL = "XXX"


def deny():
    return JSONResponse(content={"error": "Unauthorized"}, status_code=401)


def extract_token_from_header(header: str):
    parts = header.split()

    if len(parts) != 2:
        return None

    scheme = parts[0].lower()
    token = parts[1]

    if scheme != "bearer":
        return None

    return token


app = FastAPI()


@app.middleware("http")
async def auth(request: Request, call_next: Any):
    authorization = request.headers.get("authorization")

    if not authorization:
        return deny()

    token = extract_token_from_header(authorization)

    if not token:
        return deny()

    jwks_client = jwt.PyJWKClient(HANKO_API_URL)
    signing_key = jwks_client.get_signing_key_from_jwt(token)
    data = jwt.decode(
        token,
        signing_key.key,
        algorithms=["RS256"],
        audience="localhost",
        options={"verify_exp": False},
    )

    if not data:
        return deny()

    return await call_next(request)

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions