Auth
Auth 是指身份验证和授权,这是构建 Web 应用时的常见需求。身份验证意味着根据用户提供的凭据验证用户是否是他们所说的那个人。授权意味着确定他们可以采取哪些操作。
¥Auth refers to authentication and authorization, which are common needs when building a web application. Authentication means verifying that the user is who they say they are based on their provided credentials. Authorization means determining which actions they are allowed to take.
会话与令牌(Sessions vs tokens)
¥Sessions vs tokens
在用户提供其凭据(例如用户名和密码)后,我们希望允许他们使用该应用,而无需在未来的请求中再次提供其凭据。用户通常在后续请求中使用会话标识符或签名令牌(例如 JSON Web 令牌 (JWT))进行身份验证。
¥After the user has provided their credentials such as a username and password, we want to allow them to use the application without needing to provide their credentials again for future requests. Users are commonly authenticated on subsequent requests with either a session identifier or signed token such as a JSON Web Token (JWT).
会话 ID 通常存储在数据库中。它们可以立即撤销,但需要在每个请求上进行数据库查询。
¥Session IDs are most commonly stored in a database. They can be immediately revoked, but require a database query to be made on each request.
相比之下,JWT 通常不会针对数据存储进行检查,这意味着它们不能立即被撤销。此方法的优点是可以改善延迟并减少数据存储区的负载。
¥In contrast, JWT generally are not checked against a datastore, which means they cannot be immediately revoked. The advantage of this method is improved latency and reduced load on your datastore.
集成点(Integration points)
¥Integration points
可以在 服务器钩子 内部检查 Auth cookies。如果发现用户与提供的凭据匹配,则可以将用户信息存储在 locals
中。
¥Auth cookies can be checked inside server hooks. If a user is found matching the provided credentials, the user information can be stored in locals
.
指南(Guides)
¥Guides
Lucia 是基于会话的 Web 应用身份验证的一个很好的参考。它包含用于在 SvelteKit 和其他 JS 项目中实现基于会话的身份验证的示例代码片段和项目。你可以在创建新项目时使用 npx sv create
将遵循 Lucia 指南的代码添加到你的项目中,也可以为现有项目使用 npx sv add lucia
。
¥Lucia is a good reference for session-based web app auth. It contains example code snippets and projects for implementing session-based auth within SvelteKit and other JS projects. You can add code which follows the Lucia guide to your project with npx sv create
when creating a new project or npx sv add lucia
for an existing project.
身份验证系统与 Web 框架紧密耦合,因为大多数代码都用于验证用户输入、处理错误以及将用户引导到适当的下一个页面。因此,许多通用 JS 身份验证库都包含一个或多个 Web 框架。因此,许多用户会发现遵循 SvelteKit 特定的指南(例如 Lucia 中的示例)比在他们的项目中拥有多个 Web 框架更可取。
¥An auth system is tightly coupled to a web framework because most of the code lies in validating user input, handling errors, and directing users to the appropriate next page. As a result, many of the generic JS auth libraries include one or more web frameworks within them. For this reason, many users will find it preferrable to follow a SvelteKit-specific guide such as the examples found in Lucia rather than having multiple web frameworks inside their project.