网页
综合
更新时间 2026-11-16 08:45:09
Authentication - Starlette
自动蜘蛛
starlette.dev
正文约 1840 字
Starlette offers a simple but powerful interface for handling authentication and permissions. Once you've installed AuthenticationMiddleware with an appropriate authentication backend the request.user and request.auth interfaces will be available in your endpoints.
Once AuthenticationMiddleware is installed the request.user interface will be available to endpoints or other middleware.
This interface should subclass BaseUser, which provides two properties, as well as whatever other information your user model includes.
Starlette provides two built-in user implementations: UnauthenticatedUser(), and SimpleUser(username).
It is important that authentication credentials are treated as a separate concept from users. An authentication scheme should be able to restrict or grant particular privileges independently of the user identity.
The AuthCredentials class provides the basic interface that request.auth exposes:
Permissions are implemented as an endpoint decorator, that enforces that the incoming request includes the required authentication scopes.
You can include either one or multiple required scopes:
By default 403 responses will be returned when permissions are not granted. In some cases you might want to customize this, for example to hide information about the URL layout from unauthenticated users.
The status_code parameter is not supported with WebSockets. The 403 (Forbidden) status code will always be used for those.
Alternatively you might want to redirect unauthenticated users to a different page.
When redirecting users, the page you redirect them to will include the URL they originally requested at the next query param:
For class-based endpoints, you should wrap the decorator around a method on the class.
You can customise the error response sent when a AuthenticationError is raised by an auth backend:
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。