Auth - NinjaStack Docs
Description: Schema-first agentic backend framework documentation

Skip to content

# Auth

## `` gateway

ASGI/FastAPI middleware that intercepts requests and delegates to auth strategies.

### `` AuthGateway

    AuthGateway(app: Any, config: AuthConfig | None = None)

Bases: `BaseHTTPMiddleware`

Starlette middleware that authenticates requests and injects UserContext into request state.

Source code in `libs/ninja-auth/src/ninja_auth/gateway.py`

    26
    27
    28
    29
    30
    31
    def __init__(self, app: Any, config: AuthConfig | None = None) -> None:
        super().__init__(app)
        self.config = config or AuthConfig()
        self._bearer = BearerStrategy(self.config.bearer)
        self._apikey = ApiKeyStrategy(self.config.api_key)
        self._rbac = RBACPolicy(self.config.rbac)

#### `` dispatch `async`

    dispatch(
        request: Request, call_next: RequestResponseEndpoint
    ) -> Response

Authenticate the request and inject user context.

Source code in `libs/ninja-auth/src/ninja_auth/gateway.py`

    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        """Authenticate the request and inject user context."""
        # Allow public paths through without auth
        if self._is_public_path(request.url.path):
            request.state.user_context = ANONYMOUS_USER
            set_user_context(ANONYMOUS_USER)
            return await call_next(request)

        # Try each strategy in order
        user_ctx = await self._try_authenticate(request)

        if user_ctx is None:
            return JSONResponse(
                status_code=401,
                content={"detail": "Authentication required"},
            )

        # Enrich user context with RBAC-resolved permissions
        user_ctx = self._enrich_permissions(user_ctx)

        # Inject user context into request state and contextvar for agent tools
        request.state.user_context = user_ctx
        set_user_context(user_ctx)
        return await call_next(request)

### `` get_user_context

    get_user_context(request: Request) -> UserContext

FastAPI dependency to extract the authenticated user context from request state.

Usage

@app.get("/me") async def me(user: UserContext = Depends(get_user_context)): return user

Source code in `libs/ninja-auth/src/ninja_auth/gateway.py`

     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    def get_user_context(request: Request) -> UserContext:
        """FastAPI dependency to extract the authenticated user context from request state.

        Usage:
            @app.get("/me")
            async def me(user: UserContext = Depends(get_user_context)):
                return user
        """
        ctx: UserContext | None = getattr(request.state, USER_CONTEXT_KEY, None)
        if ctx is None:
            return ANONYMOUS_USER
        return ctx