Skip to content

AuthMiddleware

Factory method, returning an AuthenticationMiddleware Intentionally not named with lower snake case convention as this is a factory method returning a class. Should feel like a class.

Parameters:

Name Type Description Default
app FastAPI

The FastAPI instance the middleware should be applied to. The add_middleware function of FastAPI adds the app as first argument by default.

required
verify_authorization_header callable

A function handle that returns a list of scopes and a BaseUser

required

Examples:

def verify_authorization_header(auth_header: str) -> Tuple[List[str], FastAPIUser]:
    scopes = ["admin"]
    user = FastAPIUser(first_name="Code", last_name="Specialist", user_id=1)
    return scopes, user

app = FastAPI()
app.add_middleware(AuthMiddleware, verify_authorization_header=verify_authorization_header)
Source code in fastapi_auth_middleware/middleware.py
def AuthMiddleware(app: FastAPI, verify_authorization_header: callable):
    """ Factory method, returning an AuthenticationMiddleware
    Intentionally not named with lower snake case convention as this is a factory method returning a class. Should feel like a class.

    Args:
        app (FastAPI): The FastAPI instance the middleware should be applied to. The `add_middleware` function of FastAPI adds the app as first argument by default.
        verify_authorization_header (callable): A function handle that returns a list of scopes and a BaseUser

    Examples:
        ```python
        def verify_authorization_header(auth_header: str) -> Tuple[List[str], FastAPIUser]:
            scopes = ["admin"]
            user = FastAPIUser(first_name="Code", last_name="Specialist", user_id=1)
            return scopes, user

        app = FastAPI()
        app.add_middleware(AuthMiddleware, verify_authorization_header=verify_authorization_header)
        ```
    """
    return AuthenticationMiddleware(app, backend=FastAPIAuthBackend(verify_authorization_header))