通用OAuth

通用OAuth插件提供了一种灵活的方式来集成任何OAuth提供商的身份验证。它支持OAuth 2.0和OpenID Connect (OIDC)流程,使您能够轻松地将社交登录或自定义OAuth身份验证添加到您的应用程序中。

安装

将插件添加到您的auth配置中

要使用通用OAuth插件,请将其添加到您的auth配置中。

auth.ts
import { betterAuth } from "better-auth"
import { genericOAuth } from "better-auth/plugins"
 
export const auth = betterAuth({
    // ... 其他配置选项
    plugins: [ 
        genericOAuth({ 
            config: [ 
                { 
                    providerId: "provider-id", 
                    clientId: "test-client-id", 
                    clientSecret: "test-client-secret", 
                    discoveryUrl: "https://auth.example.com/.well-known/openid-configuration", 
                    // ... 其他配置选项
                }, 
                // 根据需要添加更多提供商
            ] 
        }) 
    ]
})

添加客户端插件

在您的身份验证客户端实例中包含通用OAuth客户端插件。

auth-client.ts
import { createAuthClient } from "better-auth/client"
import { genericOAuthClient } from "better-auth/client/plugins"
 
const authClient = createAuthClient({
    plugins: [
        genericOAuthClient()
    ]
})

使用方法

通用OAuth插件提供了用于启动OAuth流程和处理回调的端点。以下是使用方法:

启动OAuth登录

要开始OAuth登录过程:

sign-in.ts
const response = await authClient.signIn.oauth2({
  providerId: "provider-id",
  callbackURL: "/dashboard" // 用户身份验证后重定向到的路径
});

关联OAuth账户

要将OAuth账户关联到现有用户:

link-account.ts
const response = await authClient.oauth2.link({
  providerId: "provider-id",
  callbackURL: "/dashboard" // 账户关联后重定向到的路径
});

处理OAuth回调

该插件挂载了一个路由来处理OAuth回调/oauth2/callback/:providerId。这意味着默认情况下将使用${baseURL}/api/auth/oauth2/callback/:providerId作为回调URL。确保您的OAuth提供商配置为使用此URL。

配置

在将插件添加到您的auth配置时,您可以配置多个OAuth提供商。每个提供商配置对象支持以下选项:

interface GenericOAuthConfig {
  providerId: string;
  discoveryUrl?: string;
  authorizationUrl?: string;
  tokenUrl?: string;
  userInfoUrl?: string;
  clientId: string;
  clientSecret: string;
  scopes?: string[];
  redirectURI?: string;
  responseType?: string;
  prompt?: string;
  pkce?: boolean;
  accessType?: string;
  getUserInfo?: (tokens: OAuth2Tokens) => Promise<User | null>;
}
  • providerId:OAuth提供商的唯一标识符。
  • discoveryUrl:获取OAuth 2.0配置的URL(可选,但建议OIDC提供商使用)。
  • type:OAuth流程类型("oauth2"或"oidc",默认为"oauth2")。
  • authorizationUrl:授权端点的URL(如果使用discoveryUrl则可选)。
  • tokenUrl:令牌端点的URL(如果使用discoveryUrl则可选)。
  • userInfoUrl:用户信息端点的URL(如果使用discoveryUrl则可选)。
  • clientId:OAuth客户端ID。
  • clientSecret:OAuth客户端密钥。
  • scopes:要请求的OAuth作用域数组。
  • redirectURI:自定义重定向URI(可选)。
  • responseType:OAuth响应类型(默认为"code")。
  • prompt:控制用户的身份验证体验。
  • pkce:是否使用PKCE(授权码交换的证明密钥,默认为false)。
  • accessType:授权请求的访问类型。
  • getUserInfo:获取用户信息的自定义函数(可选)。

高级用法

自定义用户信息获取

您可以提供自定义的getUserInfo函数来处理特定提供商的要求:

genericOAuth({
  config: [
    {
      providerId: "custom-provider",
      // ... 其他配置选项
      getUserInfo: async (tokens) => {
        // 获取并返回用户信息的自定义逻辑
        const userInfo = await fetchUserInfoFromCustomProvider(tokens);
        return {
          id: userInfo.sub,
          email: userInfo.email,
          name: userInfo.name,
          // ... 根据需要映射其他字段
        };
      }
    }
  ]
})

映射用户信息字段

如果提供商返回的用户信息与预期格式不匹配,或者您需要映射额外的字段,您可以使用mapProfileToUser

genericOAuth({
  config: [
    {
      providerId: "custom-provider",
      // ... 其他配置选项
      mapProfileToUser: async (profile) => {
        return {
          firstName: profile.given_name,
          // ... 根据需要映射其他字段
        };
      }
    }
  ]
})

错误处理

该插件包含了对常见OAuth问题的内置错误处理。错误通常会重定向到您应用程序的错误页面,并在URL参数中包含适当的错误消息。如果未提供回调URL,用户将被重定向到Better Auth的默认错误页面。

On this page