谷歌

获取你的 Google 凭据

要使用 Google 作为社交提供者,你需要获取你的 Google 凭据。你可以通过在 Google 云控制台 创建一个新项目来获取它们。

在 Google Cloud 控制台 > 凭据 > 授权重定向 URI 中,确保将重定向 URL 设置为 http://localhost:3000/api/auth/callback/google 以进行本地开发。对于生产环境,请确保将重定向 URL 设置为你的应用域名,例如 https://example.com/api/auth/callback/google。如果你更改了认证路由的基础路径,应相应更新重定向 URL。

创建你的 Google OAuth 凭据

如果你还没有创建 OAuth 凭证,请按照以下逐步说明操作:

  1. 打开 Google Cloud 控制台API 和服务凭据
  2. 点击 创建凭据OAuth 客户端 ID
  3. 选择 Web 应用
  4. 添加你的重定向 URI:
    • http://localhost:3000/api/auth/callback/google(用于本地开发)
    • https://your-domain.com/api/auth/callback/google(用于生产环境)
  5. Client IDClient Secret 复制到你的环境变量中

这些步骤可以避免常见问题,例如 redirect_uri_mismatch

配置提供者

要配置提供者,你需要在认证配置中将 clientIdclientSecret 传递给 socialProviders.google

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

export const auth = betterAuth({
    baseURL: process.env.BETTER_AUTH_URL, 
    socialProviders: {
        google: { 
            clientId: process.env.GOOGLE_CLIENT_ID as string, 
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string, 
        }, 
    },
})

Important: Set Your Base URL

你必须配置 baseURL 以避免 redirect_uri_mismatch 错误。Better Auth 使用它来构建发送给 Google 的 OAuth 回调 URL。

选项 1:环境变量(推荐)

添加到你的 .env 文件中:

BETTER_AUTH_URL=https://your-domain.com

选项 2:显式配置

如上所示,在认证配置中直接传递 baseURL。如果不这样,回调 URL 可能会默认指向 localhost,导致 Google OAuth 在生产环境中失败。

用法

【Usage】

使用 Google 登录

【Sign In with Google】

要使用 Google 登录,你可以使用客户端提供的 signIn.social 函数。signIn 函数接收一个具有以下属性的对象:

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

  • provider:要使用的提供者。它应设置为 google
auth-client.ts
import { createAuthClient } from "better-auth/client";
const authClient = createAuthClient();

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

使用 ID 令牌通过 Google 登录

【Sign In with Google With ID Token】

要使用 ID 令牌通过 Google 登录,你可以使用 signIn.social 函数传递 ID 令牌。

【To sign in with Google using the ID Token, you can use the signIn.social function to pass the ID Token.】

当你在客户端拥有来自 Google 的 ID 令牌并希望用它在服务器端登录时,这会非常有用。

【This is useful when you have the ID Token from Google on the client-side and want to use it to sign in on the server.】

如果提供了 ID 令牌,将不会发生重定向,用户将直接登录。

auth-client.ts
const data = await authClient.signIn.social({
    provider: "google",
    idToken: {
        token: // Google ID Token,
        accessToken: // Google Access Token
    }
})

如果你想使用 Google 一次登录功能,可以参考 一次登录插件 指南。

始终要求选择一个账户

【Always ask to select an account】

如果你想始终要求用户选择一个账户,你可以将 prompt 参数传递给提供者,并将其设置为 select_account

【If you want to always ask the user to select an account, you pass the prompt parameter to the provider, setting it to select_account.】

socialProviders: {
    google: {
        prompt: "select_account", 
        clientId: process.env.GOOGLE_CLIENT_ID as string,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    },
}

请求额外的 Google 权限

【Requesting Additional Google Scopes】

如果你的应用在用户已注册后仍需要额外的 Google 权限(例如 Google Drive、Gmail 或其他 Google 服务),你可以使用相同的 Google 提供商通过 linkSocial 方法来请求这些权限。

【If your application needs additional Google scopes after the user has already signed up (e.g., for Google Drive, Gmail, or other Google services), you can request them using the linkSocial method with the same Google provider.】

auth-client.ts
const requestGoogleDriveAccess = async () => {
  await authClient.linkSocial({
    provider: "google",
    scopes: ["https://www.googleapis.com/auth/drive.file"],
  });
};

// Example usage in a React component
return (
  <button onClick={requestGoogleDriveAccess}>
    Add Google Drive Permissions
  </button>
);

这将触发一个新的 OAuth 流程,请求额外的权限范围。完成后,你的账户在数据库中将拥有新的权限范围,并且访问令牌将允许你访问所请求的 Google API。

【This will trigger a new OAuth flow that requests the additional scopes. After completion, your account will have the new scope in the database, and the access token will give you access to the requested Google APIs.】

请确保使用 Better Auth 版本 1.2.7 或更高版本,以避免在从同一提供商请求额外权限时出现“社交账户已关联”的错误。

始终获取刷新令牌

【Always get refresh token】

Google 仅在用户第一次同意你的应用时发放刷新令牌。如果用户已经授权过你的应用,后续的 OAuth 流程将只返回访问令牌,而不会返回刷新令牌。

【Google only issues a refresh token the first time a user consents to your app. If the user has already authorized your app, subsequent OAuth flows will only return an access token, not a refresh token.】

要始终获取刷新令牌,可以在提供者选项中将 accessType 设置为 offline,并将 prompt 设置为 select_account consent

【To always get a refresh token, you can set the accessType to offline, and prompt to select_account consent in the provider options.】

socialProviders: {
    google: {
        clientId: process.env.GOOGLE_CLIENT_ID as string,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
        accessType: "offline", 
        prompt: "select_account consent", 
    },
}

**撤销访问权限:**如果你想为已经授权过你应用的用户获取新的刷新令牌,你必须让他们在 Google 账户设置中撤销对你应用的访问权限,然后重新授权。

On this page