Implementing Better Auth by doanchienthangdev/omgkit
npx skills add https://github.com/doanchienthangdev/omgkit --skill 'Implementing Better Auth'// lib/auth.ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
export const auth = betterAuth({
database: prismaAdapter(prisma, { provider: "postgresql" }),
emailAndPassword: { enabled: true, requireEmailVerification: true },
session: { expiresIn: 60 * 60 * 24 * 7 },
socialProviders: {
google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! },
},
});
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 2FA 插件 |
| 会话管理 | 基于 Cookie 的安全会话,支持刷新 | 会话 |
| 速率限制 | 可配置的端点限制 | 速率限制 |
| 组织管理 | 支持多租户和角色 | 组织插件 |
// lib/auth-client.ts
import { createAuthClient } from "better-auth/client";
import { twoFactorClient, organizationClient } from "better-auth/client/plugins";
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_API_URL,
plugins: [twoFactorClient(), organizationClient()],
});
export const { signIn, signUp, signOut, useSession } = authClient;
// middleware.ts
import { auth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
const session = await auth.api.getSession({ headers: request.headers });
if (!session && !request.nextUrl.pathname.startsWith("/login")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
// 处理登录时的 2FA
const { data, error } = await authClient.signIn.email({ email, password });
if (error?.code === "TWO_FACTOR_REQUIRED") {
// 显示 2FA 输入框
const { data: verified } = await authClient.twoFactor.verify({ code: totpCode });
}
// 为用户启用 2FA
const { data } = await authClient.twoFactor.enable();
// data.totpURI 包含二维码数据
// data.backupCodes 包含恢复代码
| 建议做法 | 避免做法 |
|---|---|
| 新账户要求邮箱验证 | 存储明文密码 |
| 在认证端点启用速率限制 | 暴露详细的错误信息 |
| 使用 HttpOnly、Secure Cookie | 使用可预测的会话令牌 |
| 设置强密码要求(12+ 字符) | 允许无限次登录尝试 |
| 实现适当的会话过期机制 | 在 JWT 中存储敏感数据 |
| 记录认证事件以供审计 | 跳过 CSRF 保护 |
每周安装量
0
代码仓库
GitHub 星标数
3
首次出现时间
1970年1月1日
安全审计
// lib/auth.ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
export const auth = betterAuth({
database: prismaAdapter(prisma, { provider: "postgresql" }),
emailAndPassword: { enabled: true, requireEmailVerification: true },
session: { expiresIn: 60 * 60 * 24 * 7 },
socialProviders: {
google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! },
},
});
| Feature | Description | Reference |
|---|---|---|
| Email/Password Auth | Secure registration, login, password validation | Auth Guide |
| Social OAuth | Google, GitHub, Discord provider integration | Social Providers |
| Two-Factor Auth | TOTP-based MFA with backup codes | 2FA Plugin |
| Session Management | Secure cookie-based sessions with refresh | Sessions |
| Rate Limiting | Configurable limits per endpoint | Rate Limiting |
| Organizations | Multi-tenant support with roles | Organizations Plugin |
// lib/auth-client.ts
import { createAuthClient } from "better-auth/client";
import { twoFactorClient, organizationClient } from "better-auth/client/plugins";
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_API_URL,
plugins: [twoFactorClient(), organizationClient()],
});
export const { signIn, signUp, signOut, useSession } = authClient;
// middleware.ts
import { auth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
const session = await auth.api.getSession({ headers: request.headers });
if (!session && !request.nextUrl.pathname.startsWith("/login")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
// Handle 2FA during sign-in
const { data, error } = await authClient.signIn.email({ email, password });
if (error?.code === "TWO_FACTOR_REQUIRED") {
// Show 2FA input
const { data: verified } = await authClient.twoFactor.verify({ code: totpCode });
}
// Enable 2FA for user
const { data } = await authClient.twoFactor.enable();
// data.totpURI contains QR code data
// data.backupCodes contains recovery codes
| Do | Avoid |
|---|---|
| Require email verification for new accounts | Storing plain-text passwords |
| Enable rate limiting on auth endpoints | Exposing detailed error messages |
| Use httpOnly, secure cookies | Using predictable session tokens |
| Set strong password requirements (12+ chars) | Allowing unlimited login attempts |
| Implement proper session expiration | Storing sensitive data in JWT |
| Log authentication events for auditing | Skipping CSRF protection |
Weekly Installs
0
Repository
GitHub Stars
3
First Seen
Jan 1, 1970
Security Audits
Better Auth 最佳实践指南:集成、配置与安全设置完整教程
30,700 周安装