/login 和 /register。
前置条件
- 一个 GitHub 账号。
- 决定好生产域名。
- 5 分钟——三大平台里 GitHub 的 OAuth 流程最简单。
一步步配置
-
打开 Developer settings。github.com/settings/developers
→ OAuth Apps → New OAuth App。(如果挂在组织下,去
github.com/organizations/<org>/settings/applications。) -
填表:
回调 URL 末尾不要带斜杠。本地开发再注册一个指向
字段 值 Application name 产品名(用户在授权页会看到)。 Homepage URL https://your-domain.comAuthorization callback URL https://your-domain.com/api/auth/callback/githubhttp://localhost:3000/api/auth/callback/github的 OAuth App,dev 和 prod 用两个独立的 App。 - 生成 client secret。在 OAuth App 页点 Generate a new client secret。 立刻复制——GitHub 只显示一次。
-
写到
.env.local: -
打开按钮开关。
src/config/site.ts: -
重启
pnpm dev。环境变量是启动时读的。
Scope
Better Auth 默认请求read:user 和 user:email ——够用来填 user.name、
user.email、user.image。除非你真要在用户身份下调 GitHub API,不要再要
repo 之类的 scope。要的越多,注册转化掉得越凶。
以后真要更宽的 scope(比如读用户的 repo),在 src/lib/auth.ts 里加 scopes:
验证是否生效
- 访问
/login——“用 GitHub 登录”按钮应该出现。 - 点一下,跳到 GitHub 授权页,点 Authorize,落回
/dashboard。 - 看
account表——应该有一行providerId = 'github',挂在你的user行下。 - 先用邮箱注册,再用同邮箱的 GitHub 登一次——会合并成一个
user(账号合并对受信任 provider 是开的)。 - 看
user.image字段,应该是用户的 GitHub 头像 URL。
常见坑
- 回调 URL 带了末尾斜杠。GitHub 是字符级精确匹配。
…/callback/github/(带斜杠) 和…/callback/github(不带)不是一个东西。用不带斜杠的那个。 - dev 和 prod 共用一个 OAuth App。GitHub 免费 OAuth App 只允许一个回调 URL。
建两个 App——
MyProduct (dev)和MyProduct (prod),各用各的 client ID。 顺手把 dev 的 App 名字加 “(dev)” 后缀,授权页用户能一眼看出来这是开发环境。 - 没拿到邮箱权限。有些用户把 GitHub 上所有邮箱都设成 private。Better Auth
能跑——会回退到
noreply邮箱。如果你必须发到他主信箱,第一次登录时弹个 “请补全资料”的流程。 - 被组织限制的账号。如果用户的 GitHub 组织强制 SSO,你的 OAuth App 要先被 组织管理员批准,用户才能授权。
- client secret 只显示一次。GitHub 不会再显示第二次。丢了就重新生成——旧的立刻失效。
- 用户在 GitHub 上改了主邮箱。Better Auth 不会自动同步——
user.email留的是 注册那次的值。要追新可以加个 cron job 定期调 GitHub API 刷新。 - GitHub Enterprise 实例。默认走
github.com。如果接 GitHub Enterprise Server, 得自定义 OAuth endpoint URL,开箱不支持。
官方文档
- 创建 OAuth App — docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app
- 授权 OAuth App — docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps
- OAuth App 的 Scope — docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
- Better Auth GitHub provider — better-auth.com/docs/authentication/github