Litestar security

From litestar-org/litestar-skills · View interactive version

Litestar security is an AI agent skill from the GitHub repository litestar-org/litestar-skills. Use when working with litestar_security, SecurityPlugin, SecurityConfig, SecureController, CurrentUser, Principal, SecurityContext, or requires_role/scope/tenant/capability/assurance. Not for basic Litestar Guards.

How to use this skill

Skill file

Litestar Security

litestar-security is a declarative authentication and authorization framework for Litestar. It provides credential slots and mechanisms, unified session management, local accounts, MFA, WebAuthn passkeys, OAuth/OIDC, API keys, workload JWTs, and browser hardening.

Two separate axes, wired through two separate Litestar keywords:

Do not conflate them: the policy helpers (public, required, any_of, all_of, at_least, optional, exclude, mechanism) take mechanism names, while the guard combinators (requires_any_of, requires_all_of, requires_at_least, requires_one_of) take predicates.

Code Style Rules

Quick Reference

Plugin Registration

from litestar import Litestar, get
from litestar.di import NamedDependency

from litestar_security import (
    SecurityConfig,
    SecurityContext,
    SecurityPlugin,
    public,
)


@get("/", auth=public(), sync_to_thread=False)
def index(security_context: NamedDependency[SecurityContext]) -> dict[str, bool]:
    return {"authenticated": bool(security_context.evidence)}


app = Litestar(
    route_handlers=[index],
    plugins=[SecurityPlugin(SecurityConfig())],
)

With mechanisms configured and no inherited policy, routes default to implicit required(). With no mechanisms at all they are public.

Authentication Policy

from typing import ClassVar

from litestar import get
from litestar_security import (
    AuthenticationPolicy,
    PublicController,
    SecureController,
    all_of,
    any_of,
    at_least,
    public,
    required,
)

policy_default = required()
policy_session = required("session")
policy_either = any_of("session", "api-key")
policy_both = all_of("api-key", "service-jwt")
policy_threshold = at_least(2, "session", "api-key", "service-jwt")
policy_public = public()

Apply policy on controllers via SecureController / PublicController and on routes via auth=:

class HealthController(PublicController):
    path = "/health"

    @get("/")
    async def check(self) -> dict[str, str]:
        return {"status": "ok"}


class AccountController(SecureController):
    path = "/accounts"
    auth: ClassVar[AuthenticationPolicy] = required("session")

Use opt={"auth": ...} only on Router, Litestar, or third-party controllers that cannot subclass SecureController.

Authorization Guards

from typing import ClassVar

from litestar import get
from litestar_security import (
    AuthenticationPolicy,
    SecureController,
    required,
    requires_any_of,
    requires_role,
    requires_scope,
)


class ReportsController(SecureController):
    path = "/reports"
    auth: ClassVar[AuthenticationPolicy] = required("session")
    guards = [requires_role("analyst")]

    @get("/", guards=[requires_any_of(requires_scope("read:all"), requires_scope("read:reports"))])
    async def list_reports(self) -> list[dict[str, str]]:
        return []

Reserved Dependency Names

The plugin registers these; do not shadow them.

| Key | Type | Use |

| --- | --- | --- |

| principal | NamedDependency[Principal[User]] | Stable envelope identity plus the active user model |

| security_context | NamedDependency[SecurityContext] | Active session, evidence, snapshot, and restrictions |

| current_user | CurrentUser[User] | Narrowing shortcut (NamedDependency[User]); rejects anonymous and service principals |

| csp_nonce | csp_nonce (NamedDependency[str]) | Per-request CSP nonce when ContentSecurityPolicy.nonce_directives is non-empty |

| websocket_connect_tokens | NamedDependency[WebSocketConnectTokenIssuer] | Route-aware WebSocket connect-token issuer |

Status Code Contract

| Outcome | Status |

| --- | --- |

| Authentication failure | 401 |

| Guard denial | 403 |

| Verification unavailable (fails closed) | 503 |

<workflow>

Workflow

Step 1: Install the capabilities in use

Core install covers JWT/JWKS validation, API keys, IAP, and OIDC token verification. Use [argon2,mfa] for LocalAuth with MFA; add [passkeys] or [oauth] when needed (there is no [all] extra).

Step 2: Choose providers

Pick where identity is established — local accounts, OAuth/OIDC, Google IAP, API keys, or workload JWTs. Adding a provider makes its mechanism available; route policy decides where it is accepted. See Providers.

Step 3: Implement the authorization resolver

Implement an async resolve(principal) method that returns an AuthorizationSnapshot of granted roles, scopes, capabilities, tenant roles, and tenant IDs. Return InvalidCredentials or VerificationUnavailable for expected denial or dependency failure. It runs once per request, so guards must not perform I/O.

from litestar_security import AuthorizationSnapshot, Principal


class AppAuthorizationResolver:
    async def resolve(self, principal: Principal[User]) -> AuthorizationSnapshot:
        if not principal.is_authenticated:
            return AuthorizationSnapshot()
        user = principal.require_user()
        return AuthorizationSnapshot(
            roles=frozenset(user.roles),
            scopes=frozenset(user.scopes),
        )

Step 4: Register the plugin and set default policy

Scope an application-wide opt={"auth": ...} default to the router that owns the application's own routes, so policy-less third-party routes keep the implicit default rather than counting as declared.

Step 5: Exclude routes the application did not write

Add SecurityConfig(exclude=[...]) patterns for static files, queue dashboards, and schema browsers. See Composition.

Step 6: Harden the deployment

Apply SecurityHeadersConfig.hardened(), supply every CSP directive explicitly, and move protector keys and peppers into secret management. See Hardening.

</workflow>

<guardrails>

Guardrails

</guardrails>

<validation>

Validation Checkpoint

</validation>

<example>

Example

from dataclasses import dataclass, field
from typing import ClassVar

from litestar import Litestar, get
from litestar_security import (
    AuthenticationPolicy,
    AuthorizationSnapshot,
    CurrentUser,
    Principal,
    PublicController,
    SecureController,
    SecurityConfig,
    SecurityHeadersConfig,
    SecurityPlugin,
    required,
    requires_any_of,
    requires_role,
    requires_scope,
)


@dataclass
class User:
    id: str
    username: str
    roles: list[str] = field(default_factory=list)
    scopes: list[str] = field(default_factory=list)


class AppAuthorizationResolver:
    async def resolve(self, principal: Principal[User]) -> AuthorizationSnapshot:
        if not principal.is_authenticated:
            return AuthorizationSnapshot()
        user = principal.require_user()
        return AuthorizationSnapshot(
            roles=frozenset(user.roles),
            scopes=frozenset(user.scopes),
        )


class SystemController(PublicController):
    path = "/health"

    @get("/")
    async def health(self) -> dict[str, str]:
        return {"status": "ok"}


class OrdersController(SecureController):
    path = "/api/orders"
    auth: ClassVar[AuthenticationPolicy] = required("session")

    @get(
        "/",
        guards=[requires_any_of(requires_scope("read:all"), requires_scope("read:orders"))],
    )
    async def list_orders(self, current_user: CurrentUser[User]) -> dict[str, str]:
        return {"owner": current_user.username}

    @get("/admin", guards=[requires_role("admin")])
    async def admin_orders(self) -> list[dict[str, str]]:
        return []


security_config = SecurityConfig[User](
    authorization_resolver=AppAuthorizationResolver(),
    headers=SecurityHeadersConfig.hardened(),
    exclude=["^/static"],
)

app = Litestar(
    route_handlers=[SystemController, OrdersController],
    plugins=[SecurityPlugin(config=security_config)],
)

</example>

References Index

Cross-References

Official References

Shared Styleguide Baseline

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.