GitHub

获取你的 GitHub 凭据

要使用 GitHub 登录,你需要一个客户端 ID 和客户端密钥。你可以从 GitHub 开发者门户 获取它们。

请确保将重定向 URL 设置为 http://localhost:3000/api/auth/callback/github 以进行本地开发。对于生产环境,你应将其设置为你的应用的 URL。如果你更改了认证路由的基础路径,也应相应地更新重定向 URL。

重要提示:你必须在你的 GitHub 应用中包含 user:email 权限。详情见下文。

配置提供程序

要配置提供程序,你需要导入该提供程序并将其传递给身份验证实例的 socialProviders 选项。

auth.ts
import { betterAuth } from "better-auth"

export const auth = betterAuth({
    socialProviders: {
        github: { 
            clientId: process.env.GITHUB_CLIENT_ID as string, 
            clientSecret: process.env.GITHUB_CLIENT_SECRET as string, 
        }, 
    },
})

Sign In with GitHub

To sign in with GitHub, you can use the signIn.social function provided by the client. The signIn function takes an object with the following properties:

  • provider: The provider to use. It should be set to github.
auth-client.ts
import { createAuthClient } from "better-auth/client"
const authClient =  createAuthClient()

const signIn = async () => {
    const data = await authClient.signIn.social({
        provider: "github"
    })
}

用法

【Usage】

设置你的 Github 应用

【Setting up your Github app】

Github 有两种类型的应用:Github 应用和 OAuth 应用。

【Github has two types of apps: Github apps and OAuth apps.】

对于 OAuth 应用,你不需要做任何特别的操作(只需按照上面的步骤)。对于 GitHub 应用,你确实需要额外做一件事,那就是允许它读取用户的电子邮件:

【For OAuth apps, you don't have to do anything special (just follow the steps above). For Github apps, you DO have to add one more thing, which is enable it to read the user's email:】

  1. 创建应用后,转到 权限和事件 > 账户权限 > 电子邮件地址,然后选择“只读”
  2. 保存更改。

就是这些!现在你可以复制你应用的客户端 ID 和客户端密钥了!

【That's all! Now you can copy the Client ID and Client Secret of your app! 】

如果你收到“email_not_found”错误,那是因为你选择了 Github 应用但没有配置这部分!

为什么我没有刷新令牌?

【Why don't I have a refresh token?】

GitHub 不为 OAuth 应用发放刷新令牌。对于普通的 OAuth 应用,GitHub 会发放访问令牌,这些令牌会一直有效,除非用户撤销它们,应用撤销它们,或者一年内未使用。由于访问令牌不会像 Google 或 Discord 那样在短时间内过期,因此不需要刷新令牌。

【Github doesn't issue refresh tokens for OAuth apps. For regular OAuth apps, GitHub issues access tokens that remain valid indefinitely unless the user revokes them, the app revokes them, or they go unused for a year. There's no need for a refresh token because the access token doesn't expire on a short interval like Google or Discord.】

On this page