Authentication Functions

This module provides utility functions and decorators for authentication and authorization. These functions make it easy to protect your FastAPI endpoints and implement fine-grained access control.

Note

All guard functions live in the auth_middleware.guards package. Import them from auth_middleware.guards or from the specific sub-module auth_middleware.guards.functions.

Authentication Decorators

require_user()

Requires that a user is authenticated to access an endpoint.

from fastapi import FastAPI, Depends
from auth_middleware.guards import require_user

app = FastAPI()

@app.get("/profile", dependencies=[Depends(require_user())])
async def get_profile(request):
    user = request.state.current_user
    return {
        "id": user.id,
        "name": user.name,
        "email": user.email
    }

require_groups()

Requires that the authenticated user belongs to specific groups.

from auth_middleware.guards import require_groups

@app.get("/admin", dependencies=[Depends(require_groups(["administrators"]))])
async def admin_panel(request):
    return {"message": "Admin access granted"}

# Multiple groups (user must be in at least one)
@app.get("/staff", dependencies=[Depends(require_groups(["managers", "supervisors"]))])
async def staff_area(request):
    return {"message": "Staff access granted"}

# All of them (since 0.7.0): every listed group is required
@app.get("/board", dependencies=[Depends(require_groups(["managers", "finance"], match="all"))])
async def board(request):
    return {"message": "Both groups held"}

require_groups, require_roles and require_permissions all take match="any" (default: at least one) or match="all".

require_permissions()

Requires that the authenticated user has specific permissions.

from auth_middleware.guards import require_permissions

@app.post("/data", dependencies=[Depends(require_permissions(["write"]))])
async def create_data(request):
    return {"message": "Data created"}

# Multiple permissions (user must have all)
@app.delete("/sensitive", dependencies=[Depends(require_permissions(["admin", "delete"]))])
async def delete_sensitive(request):
    return {"message": "Sensitive data deleted"}

require_roles()

Requires that the authenticated user has specific roles.

from auth_middleware.guards import require_roles

@app.get("/reports", dependencies=[Depends(require_roles(["analyst", "manager"]))])
async def get_reports(request):
    return {"message": "Reports access granted"}

Utility Functions

get_current_user()

Retrieves the current authenticated user from the request state.

from auth_middleware.guards import get_current_user

@app.get("/user-info")
async def get_user_info(user = Depends(get_current_user)):
    if user:
        return {
            "authenticated": True,
            "user_id": user.id,
            "name": user.name
        }
    return {"authenticated": False}

Checker Classes

The guards package also exposes three standalone checker classes for building custom dependency chains.

GroupChecker

from auth_middleware.guards import GroupChecker

# Used internally by require_groups() — can also be used directly
checker = GroupChecker(groups=["admin"])

RoleChecker

from auth_middleware.guards import RoleChecker

checker = RoleChecker(roles=["analyst"])

PermissionsChecker

from auth_middleware.guards import PermissionsChecker

checker = PermissionsChecker(permissions=["write"])

Advanced Usage Examples

Combining Requirements

You can combine multiple authentication requirements:

from fastapi import Depends
from auth_middleware.guards import require_user, require_groups, require_permissions

# Requires user to be authenticated AND in admin group AND have delete permission
@app.delete(
    "/admin/users/{user_id}",
    dependencies=[
        Depends(require_user()),
        Depends(require_groups(["administrators"])),
        Depends(require_permissions(["user:delete"]))
    ]
)
async def delete_user(user_id: str, request):
    return {"message": f"User {user_id} deleted"}

Optional Authentication

For endpoints that work with or without authentication:

from typing import Optional
from auth_middleware.guards import get_current_user

@app.get("/public-data")
async def get_public_data(user: Optional[dict] = Depends(get_current_user)):
    base_data = {"public": "This is public information"}

    if user:
        base_data["private"] = "This is additional info for authenticated users"
        base_data["user_name"] = user.name

    return base_data

Custom Authorization Logic

Create custom authorization functions:

from fastapi import HTTPException, Depends
from auth_middleware.guards import get_current_user

def require_user_or_api_key():
    async def check_auth(request, user = Depends(get_current_user)):
        if user:
            return user

        api_key = request.headers.get("X-API-Key")
        if api_key and validate_api_key(api_key):
            return {"type": "api_key", "key": api_key}

        raise HTTPException(status_code=401, detail="Authentication required")

    return check_auth

@app.get("/api/data", dependencies=[Depends(require_user_or_api_key())])
async def get_api_data(request):
    return {"data": "Sensitive information"}

Error Handling

The authentication functions automatically raise appropriate HTTP exceptions:

# require_user()        raises HTTPException(401) if not authenticated
# require_groups()      raises HTTPException(403) if user lacks required groups
# require_permissions() raises HTTPException(403) if user lacks permissions
# require_roles()       raises HTTPException(403) if user lacks required roles

API Reference

auth_middleware.guards.functions.get_current_user() → Callable[[...], Any][source]

Returns the current user object if it exists

auth_middleware.guards.functions.get_identity(*, allow_synthetic: bool = False, on_unauthenticated: Callable[[Request], Exception] | None = None) → Callable[[...], Awaitable[Identity]][source]

Like require_authenticated() but returns an immutable Identity.

Identity.groups resolves the lazy await user.groups; name falls back to the sub and email to "".

async auth_middleware.guards.functions.has_groups(request: Request, allowed_groups: list[str]) → bool[source]

Check if the user has the required groups asynchronously

Parameters:
  • request (Request) – FastAPI request object

  • allowed_groups (List[str]) – a list of required groups

Returns:

True if the user has the required groups, False otherwise

Return type:

bool

async auth_middleware.guards.functions.has_permissions(request: Request, allowed_permissions: list[str]) → bool[source]

Check if the user has the required permissions asynchronously

Parameters:
  • request (Request) – FastAPI request object

  • allowed_permissions (List[str]) – a list of required permissions

Returns:

True if the user has the required permissions, False otherwise

Return type:

bool

async auth_middleware.guards.functions.has_roles(request: Request, allowed_roles: list[str]) → bool[source]

Check if the user has the required roles asynchronously

Parameters:
  • request (Request) – FastAPI request object

  • allowed_roles (List[str]) – a list of required roles

Returns:

True if the user has the required roles, False otherwise

Return type:

bool

auth_middleware.guards.functions.require_authenticated(*, allow_synthetic: bool = False, on_unauthenticated: Callable[[Request], Exception] | None = None) → Callable[[...], Awaitable[User]][source]

Fail-closed authentication guard.

Unlike require_user(), it never lets the request through when AUTH_MIDDLEWARE_DISABLED is set: the placeholder synthetic user the middleware creates then is rejected (401) unless allow_synthetic=True.

Parameters:
  • allow_synthetic – Accept the placeholder user (development only).

  • on_unauthenticated – Builds the exception to raise instead of the default 401 with WWW-Authenticate: Bearer (e.g. a uniform problem body).

Returns:

A dependency returning the authenticated User.

Raises:

HTTPException – 401 when there is no user (or only the synthetic one).

auth_middleware.guards.functions.require_groups(allowed_groups: list[str], *, match: str = 'any') → Callable[[...], Any][source]

Check if the user has the required groups

Parameters:

allowed_groups (List[str]) – a list of required groups

auth_middleware.guards.functions.require_permissions(allowed_permissions: list[str], *, match: str = 'any') → Callable[[...], Any][source]

Check if the user has the required permissions

By default the user needs at least one of allowed_permissions (match="any", like require_groups and require_roles); pass match="all" to require every one of them.

Parameters:

allowed_permissions (List[str]) – a list of required permissions

auth_middleware.guards.functions.require_roles(allowed_roles: list[str], *, match: str = 'any') → Callable[[...], Any][source]

Check if the user has the required roles

Parameters:

allowed_roles (List[str]) – a list of required roles

auth_middleware.guards.functions.require_user() → Callable[[...], Any][source]

Check if the user is authenticated

class auth_middleware.guards.group_checker.GroupChecker(allowed_groups: list[str], *, match: str = 'any')[source]

Bases: object

Controls if user has the required group (user_type)

__init__(allowed_groups: list[str], *, match: str = 'any') → None[source]
class auth_middleware.guards.role_checker.RoleChecker(allowed_roles: list[str], *, match: str = 'any')[source]

Bases: object

Controls if user has the required role (user_type)

__init__(allowed_roles: list[str], *, match: str = 'any') → None[source]
class auth_middleware.guards.permissions_checker.PermissionsChecker(allowed_permissions: list[str], *, match: str = 'any')[source]

Bases: object

Controls if user has the required permissions (user_type)

__init__(allowed_permissions: list[str], *, match: str = 'any') → None[source]

require_authenticated()

Fail-closed authentication guard (since 0.7.0). Unlike require_user(), it is not disabled by AUTH_MIDDLEWARE_DISABLED: the placeholder synthetic user the middleware creates then is rejected with 401 unless allow_synthetic=True. on_unauthenticated(request) may return your own exception (for example a uniform problem body); the default is 401 with WWW-Authenticate: Bearer.

from auth_middleware.guards import require_authenticated

@app.get("/me")
async def me(user=Depends(require_authenticated())):
    return {"id": user.id}

get_identity()

Same checks, but returns an immutable Identity(sub, email, name, groups) with the lazy groups already resolved. name falls back to sub and email to "".

from auth_middleware.guards import get_identity
from auth_middleware.types.identity import Identity

@app.get("/whoami")
async def whoami(identity: Identity = Depends(get_identity())):
    return {"sub": identity.sub, "groups": list(identity.groups)}