Better Auth
结合 Better Auth 使用 Hono 进行身份验证。
Better Auth 是一个不依赖特定框架的 TypeScript 身份验证和授权框架。它开箱即提供全面的功能,并拥有插件生态,让添加高级功能更加简单。
配置
- 安装框架:
sh
# npm
npm install better-auth
# bun
bun add better-auth
# pnpm
pnpm add better-auth
# yarn
yarn add better-auth- 在
.env文件中添加所需的环境变量:
sh
BETTER_AUTH_SECRET=<generate-a-secret-key> (e.g. D27gijdvth3Ul3DjGcexjcFfgCHc8jWd)
BETTER_AUTH_URL=<url-of-your-server> (e.g. http://localhost:1234)- 创建 Better Auth 实例
ts
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import prisma from '@/db/index'
import env from '@/env'
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: 'postgresql',
}),
// Allow requests from the frontend development server
trustedOrigins: ['http://localhost:5173'],
emailAndPassword: {
enabled: true,
},
socialProviders: {
github: {
clientId: env.GITHUB_CLIENT_ID,
clientSecret: env.GITHUB_CLIENT_SECRET,
},
google: {
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET,
},
},
})
export type AuthType = {
user: typeof auth.$Infer.Session.user | null
session: typeof auth.$Infer.Session.session | null
}上述代码:
- 配置数据库使用 Prisma ORM 和 PostgreSQL
- 指定受信任的来源
- 受信任的来源是允许向认证 API 发出请求的应用,通常就是你的客户端(前端)
- 其他所有来源都会自动被阻止
- 启用邮箱/密码身份验证,并配置社交登录提供商。
- 将所需的所有模型、字段和关系生成到 Prisma 模式文件:
sh
bunx @better-auth/cli generate- 在
routes/auth.ts中创建处理认证 API 请求的 API 处理程序
此路由使用 Better Auth 提供的处理程序,处理 /api/auth 端点上的所有 POST 和 GET 请求。
ts
import { Hono } from 'hono'
import { auth } from '../lib/auth'
import type { AuthType } from '../lib/auth'
const router = new Hono<{ Bindings: AuthType }>({
strict: false,
})
router.on(['POST', 'GET'], '/auth/*', (c) => {
return auth.handler(c.req.raw)
})
export default router- 挂载路由
以下代码用于挂载路由。
ts
import { Hono } from "hono";
import type { AuthType } from "../lib/auth"
import auth from "@/routes/auth";
const app = new Hono<{ Variables: AuthType }>({
strict: false,
});
const routes = [auth, ...other routes] as const;
routes.forEach((route) => {
app.basePath("/api").route("/", route);
});
export default app;