Exception Handling

This module defines the custom exceptions used throughout the auth-middleware library. These exceptions provide specific error handling for authentication and authorization scenarios.

Exception Types

InvalidTokenException

The primary exception raised during token validation failures. Carries an HTTP status code and detail message.

Common causes:

  • Invalid or expired JWT tokens

  • Missing or malformed Authorization header

  • No public key found for the token

  • Token signature verification failure

from auth_middleware.exceptions import InvalidTokenException

try:
    user = await authenticate_user(token)
except InvalidTokenException as e:
    return JSONResponse(
        status_code=e.status_code,
        content={"error": "Token error", "detail": e.detail}
    )

AuthenticationError

Raised when low-level authentication fails (e.g., HMAC computation, credential decoding).

from auth_middleware.exceptions import AuthenticationError

try:
    result = await provider.verify_token(credentials)
except AuthenticationError as e:
    logger.warning(f"Authentication error: {e}")

InvalidAuthorizationException

Raised when the Authorization header is present but malformed (wrong scheme, missing parts).

from auth_middleware.exceptions import InvalidAuthorizationException

InvalidCredentialsException

Raised when Basic Auth credentials are invalid (wrong username or password).

from auth_middleware.exceptions import InvalidCredentialsException

UserNotFoundError

Raised when a user cannot be found in the identity provider.

from auth_middleware.exceptions import UserNotFoundError

PasswordPolicyError

Raised when a password change fails due to policy requirements.

from auth_middleware.exceptions import PasswordPolicyError

Exception Handling Patterns

Global Exception Handler

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from auth_middleware.exceptions import InvalidTokenException, AuthenticationError

app = FastAPI()

@app.exception_handler(InvalidTokenException)
async def invalid_token_handler(request: Request, exc: InvalidTokenException):
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "error": "token_error",
            "message": exc.detail,
        }
    )

@app.exception_handler(AuthenticationError)
async def authentication_error_handler(request: Request, exc: AuthenticationError):
    return JSONResponse(
        status_code=401,
        content={
            "error": "authentication_failed",
            "message": str(exc),
        }
    )

API Reference

Auth-middleware exceptions.

exception auth_middleware.exceptions.AuthenticationError(detail: str = 'Invalid credentials')[source]

Bases: HTTPException

Raised when credentials are invalid or the session has expired.

__init__(detail: str = 'Invalid credentials') None[source]
exception auth_middleware.exceptions.ChallengeRequiredError(challenge_name: str, session: str)[source]

Bases: Exception

Internal signal: Cognito returned a challenge instead of tokens.

Not raised directly to the HTTP layer — caught by the service and converted to a ChallengeResponse.

__init__(challenge_name: str, session: str) None[source]
exception auth_middleware.exceptions.InvalidAuthorizationException(status_code: Annotated[int, Doc('\n                HTTP status code to send to the client.\n                ')], detail: Annotated[Any, Doc('\n                Any data to be sent to the client in the `detail` key of the JSON\n                response.\n                ')] = None, headers: Annotated[dict[str, str] | None, Doc('\n                Any headers to send to the client in the response.\n                ')] = None)[source]

Bases: HTTPException

Exception thrown when the authorization header is invalid

Parameters:

HTTPException (_type_) – _description_

exception auth_middleware.exceptions.InvalidChallengeError(detail: str = 'Invalid or expired challenge')[source]

Bases: HTTPException

Raised when the challenge response is incorrect or the session is expired.

__init__(detail: str = 'Invalid or expired challenge') None[source]
exception auth_middleware.exceptions.InvalidCredentialsException(status_code: Annotated[int, Doc('\n                HTTP status code to send to the client.\n                ')], detail: Annotated[Any, Doc('\n                Any data to be sent to the client in the `detail` key of the JSON\n                response.\n                ')] = None, headers: Annotated[dict[str, str] | None, Doc('\n                Any headers to send to the client in the response.\n                ')] = None)[source]

Bases: HTTPException

Exception thrown when the user credentials are invalid

Parameters:

HTTPException (_type_) – _description_

exception auth_middleware.exceptions.InvalidTokenException(status_code: Annotated[int, Doc('\n                HTTP status code to send to the client.\n                ')], detail: Annotated[Any, Doc('\n                Any data to be sent to the client in the `detail` key of the JSON\n                response.\n                ')] = None, headers: Annotated[dict[str, str] | None, Doc('\n                Any headers to send to the client in the response.\n                ')] = None)[source]

Bases: HTTPException

Exception thrown when the token is invalid

Parameters:

HTTPException (_type_) – _description_

exception auth_middleware.exceptions.MfaSetupError(detail: str = 'MFA setup failed')[source]

Bases: HTTPException

Raised when a TOTP setup or verification operation fails.

__init__(detail: str = 'MFA setup failed') None[source]
exception auth_middleware.exceptions.PasswordPolicyError(detail: str = 'Password does not meet policy requirements')[source]

Bases: HTTPException

Raised when the new password does not meet the password policy.

__init__(detail: str = 'Password does not meet policy requirements') None[source]
exception auth_middleware.exceptions.UserNotFoundError(detail: str = 'User not found')[source]

Bases: HTTPException

Raised when the requested user does not exist.

__init__(detail: str = 'User not found') None[source]