EasyStarter logoEasyStarter

认证系统

用户认证与授权

概述

EasyStarter 使用 Better Auth 进行认证,提供完整的用户管理解决方案。

支持的认证方式

方式说明
邮箱/密码传统注册方式,支持邮箱验证
GitHub OAuth使用 GitHub 账号一键登录
Google OAuth使用 Google 账号一键登录

配置

环境变量

# 必需
AUTH_SECRET=your-secret-key

# OAuth(可选)
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

# 邮件(用于验证)
RESEND_API_KEY=your-resend-api-key

前端使用

登录

import { authClient } from "@/lib/auth-client";

// 邮箱/密码登录
await authClient.signIn.email({
	email: "user@example.com",
	password: "password123",
});

// OAuth 登录
await authClient.signIn.social({ provider: "github" });
await authClient.signIn.social({ provider: "google" });

登出

await authClient.signOut();

获取当前用户

const { data: session } = authClient.useSession();
const user = session?.user;

会话管理

Better Auth 自动管理会话:

  • 基于 Cookie 的会话存储
  • 自动刷新,防止过期
  • 跨标签页同步

路由保护

使用认证中间件保护路由:

// 在路由组件中
import { createFileRoute, redirect } from "@tanstack/react-router";

export const Route = createFileRoute("/dashboard")({
	beforeLoad: async ({ context }) => {
		if (!context.user) {
			throw redirect({ to: "/sign-in" });
		}
	},
});

On this page