身份验证
学习如何在 ShipSaaS 中使用 Better Auth 设置和使用身份验证
ShipSaaS 使用 Better Auth 进行身份验证,这是一个 TypeScript 原生的身份验证库。
设置
环境变量
生成一个随机密钥并添加到环境变量文件中:
openssl rand -base64 32.env
BETTER_AUTH_SECRET=your_generated_secret网站配置
一般情况下,保持默认配置即可,如果需要更改,可以修改 src/config/website.ts 中 auth 配置:
export const websiteConfig: WebsiteConfig = {
// ...
auth: {
enable: true,
enableGoogleLogin: true, // 是否启用 Google 登录
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 添加到环境变量文件中:
.env
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret如果您正在设置环境,现在可以回到环境配置文档并继续。本文档的其余部分可以稍后阅读。
身份验证系统架构
ShipSaaS 中的身份验证系统包含以下组件:
src
auth
auth.ts
client.ts
types.ts
components
routes
middlewares
身份验证路由
ShipSaaS 提供以下身份验证路由:
| 路由 | 描述 |
|---|---|
| /auth/login | 登录页面 |
| /auth/register | 注册页面 |
| /auth/forgot-password | 密码重置请求 |
| /auth/reset-password | 密码重置表单 |
| /auth/error | 错误页面 |
参考资料
下一步
现在您了解了 ShipSaaS 中身份验证的工作原理,您可能想要探索这些相关功能: