jwt_auth_middleware

class auth_middleware.jwt_auth_middleware.AuthFailure(status_code: int, reason: Literal['invalid_token', 'bad_scheme', 'internal', 'unavailable'])[source]

Bases: object

What an error_responder is told about a rejected request.

reason is meant for logs and metrics; the exception text is never passed, and by default nothing of it reaches the response body.

__init__(status_code: int, reason: Literal['invalid_token', 'bad_scheme', 'internal', 'unavailable']) → None
reason: Literal['invalid_token', 'bad_scheme', 'internal', 'unavailable']
status_code: int
class auth_middleware.jwt_auth_middleware.JwtAuthMiddleware(app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]], auth_provider: JWTProvider, *args: Any, canonical_bearer_scheme: bool = False, path_prefix: str | None = None, error_responder: Callable[[Request, AuthFailure], Response] | None = None, strict: bool = False, **kwargs: Any)[source]

Bases: BaseHTTPMiddleware

JWT Authorization middleware for FastAPI Adds the current user to the request state.

Every option below is keyword-only and defaults to the historical behaviour.

Parameters:
  • app – The ASGI application.

  • auth_provider – The JWT provider validating tokens.

  • canonical_bearer_scheme – Treat the Authorization scheme case-insensitively (RFC 7235): bearer/BEARER are rewritten to Bearer before validation. Other schemes keep their own rejection status.

  • path_prefix – Only requests whose path equals the prefix or starts with prefix + "/" are authenticated; others skip the middleware entirely and request.state.current_user is not set for them. Useful when other apps are mounted inside this one with their own middleware.

  • error_responder – Builds the response for invalid token, bad scheme and internal errors from (request, AuthFailure). The default keeps the {"detail": ...} JSON bodies.

  • strict – Raise RuntimeError at construction when AUTH_MIDDLEWARE_DISABLED is set or the provider’s settings have jwt_token_verification_disabled=True.

__init__(app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]], auth_provider: JWTProvider, *args: Any, canonical_bearer_scheme: bool = False, path_prefix: str | None = None, error_responder: Callable[[Request, AuthFailure], Response] | None = None, strict: bool = False, **kwargs: Any) → None[source]
async dispatch(request: Request, call_next: Callable[[Request], Awaitable[Response]]) → Response | JSONResponse[source]
async get_current_user(request: Request) → User | None[source]

Get current logged in and active user

Raises:

HTTPException – _description_

Returns:

Domain object.

Return type:

User