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.
1. The Security Pipeline
Section titled “1. The Security Pipeline”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
| Component | Scope | When | Use For |
|---|---|---|---|
| Middleware | Global | Outermost | CORS, CSRF, Rate Limiting |
| Guard | Scoped | After Routing | Authentication, Role Checks |
2. Using Guards
Section titled “2. Using Guards”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.
AuthGuard
Section titled “AuthGuard”The built-in AuthGuard ensures a valid user session or token is present.
from lexigram.web import Controller, getfrom 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"}RoleGuard
Section titled “RoleGuard”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"3. Custom Guards
Section titled “3. Custom Guards”You can implement custom logic by extending BaseGuard.
from lexigram.web.security.guards import BaseGuardfrom 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_ips4. Error Mapping
Section titled “4. Error Mapping”When a Guard fails, Lexigram automatically returns a standardized HTTP error.
| Guard Failure | HTTP Status | Error Type |
|---|---|---|
| Authentication | 401 | AuthenticationError |
| Authorization | 403 | PermissionError |
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.