Skip to content
GitHubDiscord

Authentication

Lexigram provides a robust, multi-layered approach to security that separates identity verification from business logic. Most authentication tasks are handled within the Request Pipeline using Guards.

For a deep dive into the underlying transport layer, see the Web & HTTP Package.


Understanding where security checks happen is critical for performance and safety.

graph TD
    Req[Client Request] --> MW[Middleware: CORS/CSRF]
    MW --> Route[Router: Match Path]
    Route --> Guard[Guards: Authenticate & Authorize]
    Guard --> Handler[Handler: Controller Logic]
    
    subgraph Security Layer
        Guard
    end
ComponentScopeWhenUse For
MiddlewareGlobalOutermostCORS, CSRF, Rate Limiting
GuardScopedAfter RoutingAuthentication, Role Checks

Guards are the primary way to protect routes. They can be applied to an entire controller or a specific method using the @use_guards decorator.

The built-in AuthGuard ensures a valid user session or token is present.

from lexigram.web import Controller, get
from lexigram.web.security.guards import use_guards, AuthGuard
class ProfileController(Controller):
prefix = "/api/profile"
@get("/")
@use_guards(AuthGuard)
async def get_profile(self) -> dict:
# If execution reaches here, the user is authenticated
return {"user": "geezmo"}

Restrict access based on user roles (e.g., admin, editor).

from lexigram.web.security.guards import RoleGuard
@use_guards(RoleGuard("admin"))
class AdminPageController(Controller):
prefix = "/admin"

You can implement custom logic by extending BaseGuard.

from lexigram.web.security.guards import BaseGuard
from lexigram.web import Request
class IPWhitelistGuard(BaseGuard):
async def can_activate(self, request: Request) -> bool:
allowed_ips = ["127.0.0.1", "10.0.0.1"]
return request.client.host in allowed_ips

When a Guard fails, Lexigram automatically returns a standardized HTTP error.

Guard FailureHTTP StatusError Type
Authentication401AuthenticationError
Authorization403PermissionError

These are mapped to Problem Details (RFC 7807) by default.

[!TIP] Since Lexigram uses the Result Pattern, you can also return authentication errors directly from your services, which the framework will automatically map to the appropriate HTTP status code.