Google

获取 Google 凭证

要使用 Google 作为社交提供商,你需要获取 Google 凭证。你可以通过在 Google Cloud Console 中创建新项目来获取它们。

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

配置提供商

要配置提供商,你需要在 auth 配置中将 clientIdclientSecret 传递给 socialProviders.google

auth.ts
import { betterAuth } from "better-auth"
 
export const auth = betterAuth({
    socialProviders: {
        google: { 
            clientId: process.env.GOOGLE_CLIENT_ID as string, 
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string, 
        }, 
    },
})

使用方法

使用 Google 登录

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

  • 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 Token 通过 Google 登录

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

当你从客户端获取了 Google 的 ID Token 并想在服务器上使用它来登录时,这很有用。

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

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

如果你想使用 Google 一键登录,可以参考 One Tap 插件 指南。

On this page