Back to list
Sobansaud

fastapi-jwt-auth

by Sobansaud

0🍴 0📅 Jan 21, 2026

SKILL.md


name: fastapi-jwt-auth description: This skill should be used when implementing secure, reusable JWT verification dependency for FastAPI routes. It ensures strict user isolation and identity verification using Better Auth secrets.

FastAPI JWT Auth Middleware

This skill provides a secure, reusable JWT verification dependency for FastAPI routes.

Purpose

Implementing a secure, reusable JWT verification dependency for FastAPI routes to ensure strict user isolation and identity verification.

Capabilities

  • Extracting Authorization: Bearer <token> from request headers.
  • Verifying token signature using the BETTER_AUTH_SECRET environment variable.
  • Decoding JWT payloads to extract authenticated user_id and email.
  • Performing path-level validation to ensure the authenticated user_id matches the {user_id} variable in the route path.
  • Standardized error handling with HTTPException:
    • 401 Unauthorized: Token missing, invalid signature, or expired.
    • 403 Forbidden: Authenticated user ID does not match the requested path resource.
  • Providing a current_user object injectable directly into route functions.

Implementation Details

Security Pattern

Using python-jose[cryptography] or PyJWT to handle verification.

from fastapi import Depends, HTTPException, status, Request
from jose import jwt

async def get_current_user(user_id: str, request: Request):
    auth_header = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Invalid auth header")

    token = auth_header.split(" ")[1]
    payload = jwt.decode(token, BETTER_AUTH_SECRET, algorithms=["HS256"])
    token_user_id = payload.get("user_id")

    if token_user_id != user_id:
        raise HTTPException(status_code=403, detail="Not authorized for this resource")

    return payload

Best Practices

  • Loading BETTER_AUTH_SECRET only once at startup.
  • Always validating the user_id against the path to prevent ID enumeration/access bypass.
  • Using dependency injection to keep route logic clean and testable.

Score

Total Score

40/100

Based on repository quality metrics

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

0/10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 100以上

0/15
最近の活動

3ヶ月以内に更新がある

0/10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

0/5

Reviews

💬

Reviews coming soon