Authentication & Authorization
Relevant source files
The following files were used as context for generating this wiki page:
Starlette provides a modular and extensible system for handling authentication and authorization in ASGI applications. The system is built around three primary components: the AuthenticationMiddleware, which processes incoming connections; AuthenticationBackend implementations, which define how credentials are validated; and the @requires decorator, which enforces access control based on user scopes.
The architecture decouples the mechanism of authentication (e.g., Basic Auth, JWT, Sessions) from the application logic. Successful authentication populates the ASGI scope with user information and credentials, making them accessible via request.user and request.auth in downstream handlers.
Core Architecture
The authentication flow begins at the middleware layer. When a request or WebSocket connection enters the application, the AuthenticationMiddleware delegates the validation to a developer-defined backend.
Authentication Middleware
The AuthenticationMiddleware is responsible for wrapping the ASGI application and intercepting "http" and "websocket" scope types. It utilizes an AuthenticationBackend to return a tuple of (AuthCredentials, BaseUser). If no credentials are provided, it defaults to an UnauthenticatedUser.
Sources: starlette/middleware/authentication.py:18-45, starlette/authentication.py:126-140
Logic Flow Diagram
The following diagram illustrates how a request is processed by the authentication system:
Authentication Interfaces
Starlette defines base classes and data structures to standardize user identity and credential management.
Key Classes
| Class | Description | Relevant Methods/Properties |
|---|---|---|
AuthenticationBackend | Interface for credential validation. | authenticate(conn) |
AuthCredentials | Container for a list of granted scopes. | scopes |
BaseUser | Abstract base class for user objects. | is_authenticated, display_name, identity |
SimpleUser | A basic implementation of an authenticated user. | username |
UnauthenticatedUser | Implementation representing an anonymous user. | is_authenticated (returns False) |
Sources: starlette/authentication.py:107-160
Backend Implementation
A custom backend must implement the authenticate method. It receives an HTTPConnection (which abstracts both HTTP requests and WebSockets) and should return a tuple of credentials and a user object.
class BasicAuth(AuthenticationBackend):
async def authenticate(self, request: HTTPConnection):
if "Authorization" not in request.headers:
return None
# ... validation logic ...
return AuthCredentials(["authenticated"]), SimpleUser(username)
Sources: tests/test_authentication.py:31-48
Authorization and Scopes
Authorization in Starlette is handled by checking "scopes" associated with the authenticated user. A scope is a string representing a permission or role (e.g., "authenticated", "admin").
The @requires Decorator
The @requires decorator is used to protect endpoints. It inspects the request or websocket argument of the decorated function to verify if the required scopes are present in request.auth.scopes.
Sources: starlette/authentication.py:27-101
Configuration Options for @requires
| Parameter | Type | Default | Description |
|---|---|---|---|
scopes | str | Sequence[str] | Required | The scope(s) required to access the endpoint. |
status_code | int | 403 | HTTP status code to return on authorization failure. |
redirect | str | None | None | Route name to redirect to on failure (HTTP only). |
Sources: starlette/authentication.py:27-32
Data Relationships
The authentication system integrates tightly with the ASGI scope and Starlette's application structure.
Error Handling
The AuthenticationMiddleware allows for custom error handling via the on_error parameter.
- HTTP: By default, it returns a
PlainTextResponsewith a 400 status code if anAuthenticationErroris raised. - WebSockets: The connection is automatically closed with code 1000.
- Customization: Developers can provide a callable with the signature
(conn: HTTPConnection, exc: AuthenticationError) -> Response.
Sources: starlette/middleware/authentication.py:41-51, tests/test_authentication.py:236-238
Summary
The Authentication & Authorization module in Starlette provides a standardized way to identify users and control access to resources. By utilizing middleware for credential processing and decorators for scope-based access control, the system ensures that security logic remains separate from business logic. The use of the HTTPConnection abstraction allows the same authentication backends to be shared between standard HTTP routes and WebSocket endpoints.
Sources: starlette/authentication.py:1-160, starlette/middleware/authentication.py:1-51