Appearance
Better Auth
使用 Hono 配合 Better Auth 进行身份验证。
🌐 Using Hono with Better Auth for authentication.
Better Auth 是一个与框架无关的 TypeScript 认证和授权框架。它开箱即用地提供了一整套功能,并包括一个插件生态系统,简化了添加高级功能的过程。
🌐 Better Auth is a framework-agnostic authentication and authorization framework for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities.
配置
🌐 Configuration
- 安装框架:
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
}以上代码:
🌐 The above code:
- 设置数据库以使用 Prisma ORM 和 PostgreSQL
- 指定受信任的来源
- 受信任的来源是被允许向身份验证 API 发出请求的应用。通常,那是你的客户端(前端)。
- 所有其他来源将被自动阻止。
- 它支持电子邮件/密码身份验证并配置社交登录提供程序。
- 生成 Prisma schema 文件所需的所有模型、字段和关系:
sh
bunx @better-auth/cli generate- 在
routes/auth.ts中为身份验证 API 请求创建 API 处理程序
此路由使用 Better Auth 提供的处理程序来处理所有对 /api/auth 端点的 POST 和 GET 请求。
🌐 This route uses the handler provided by Better Auth to serve all POST and GET requests to the /api/auth endpoint.
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- 挂载路由
以下代码挂载路由。
🌐 The code below mounts the route.
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;另请参阅
🌐 See also