身份验证
学习如何在 TanStarter 中使用 Better Auth 设置和使用身份验证
TanStarter 使用 Better Auth 进行身份验证,这是一个 TypeScript 原生的身份验证库。
设置
网站配置
在 src/config/website.ts 中配置身份验证选项:
export const websiteConfig: WebsiteConfig = {
// ...
auth: {
enable: true,
enableGoogleLogin: true,
enableCredentialLogin: true, // 启用邮箱密码登录
enableDeleteAccount: true,
},
// ...
};| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| enable | boolean | true | 启用/禁用身份验证 |
| enableGoogleLogin | boolean | true | 启用 Google OAuth 登录 |
| enableCredentialLogin | boolean | false | 启用邮箱密码登录 |
| enableDeleteAccount | boolean | true | 允许用户删除账户 |
Google OAuth(可选)
如果启用了 Google 登录,需要配置 Google OAuth:
- 进入到 Google Cloud Console
- 创建新项目
- 导航到 APIs & Services > Credentials
- 点击 Create Credentials > OAuth client ID
- 如果需要,配置 OAuth 同意屏幕
- 选择 Web application 作为应用程序类型
- 将
http://localhost:3000和https://your-domain.com添加到 Authorized JavaScript origins - 将
http://localhost:3000/api/auth/callback/google和https://your-domain.com/api/auth/callback/google添加到 Authorized redirect URIs - 将 Client ID 和 Client Secret 添加到环境变量文件中:
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret如果您正在设置环境,现在可以回到环境配置文档并继续。本文档的其余部分可以稍后阅读。
环境配置
设置环境变量
身份验证系统架构
TanStarter 中的身份验证系统包含以下组件:
auth.ts
client.ts
types.ts
身份验证路由
TanStarter 提供以下身份验证路由:
| 路由 | 描述 |
|---|---|
/auth/login | 登录页面 |
/auth/register | 注册页面 |
/auth/forgot-password | 密码重置请求 |
/auth/reset-password | 密码重置表单 |
/auth/error | 错误页面 |
参考资料
下一步
现在您了解了 TanStarter 中身份验证的工作原理,您可能想要探索这些相关功能:
TanStarter 文档