OAuth 代理

一个代理插件,允许你代理 OAuth 请求。适用于开发和预览部署场景,在这些场景中无法提前知道重定向 URL 以添加到 OAuth 提供商中。

【A proxy plugin, that allows you to proxy OAuth requests. Useful for development and preview deployments where the redirect URL can't be known in advance to add to the OAuth provider. 】

安装

【Installation】

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

auth.ts
import { betterAuth } from "better-auth"
import { oAuthProxy } from "better-auth/plugins"

export const auth = betterAuth({
    plugins: [ 
        oAuthProxy({ 
            productionURL: "https://my-main-app.com", // Optional - if the URL isn't inferred correctly
            currentURL: "http://localhost:3000", // Optional - if the URL isn't inferred correctly
        }), 
    ] 
})

Add redirect URL to your OAuth provider

为了让代理服务器正常工作,你需要在社交提供商配置中传递与 OAuth 提供商注册的主生产应用的重定向 URL。对于你想要代理请求的每个社交提供商,都需要进行此操作。

export const auth = betterAuth({
   plugins: [
       oAuthProxy(),
   ], 
   socialProviders: {
        github: {
            clientId: "your-client-id",
            clientSecret: "your-client-secret",
            redirectURI: "https://my-main-app.com/api/auth/callback/github"
        }
   }
})

它是如何工作的

【How it works】

该插件为你的服务器添加了一个端点,用于代理 OAuth 请求。当你启动社交登录时,它会将重定向 URL 设置为此代理端点。在 OAuth 提供者重定向回你的服务器后,插件会将用户转发到原始回调 URL。

【The plugin adds an endpoint to your server that proxies OAuth requests. When you initiate a social sign-in, it sets the redirect URL to this proxy endpoint. After the OAuth provider redirects back to your server, the plugin then forwards the user to the original callback URL.】

await authClient.signIn.social({
    provider: "github",
    callbackURL: "/dashboard" // the plugin will override this to something like "http://localhost:3000/api/auth/oauth-proxy?callbackURL=/dashboard"
})

当 OAuth 提供者将用户返回到你的服务器时,插件会自动将他们重定向到预期的回调 URL。

【When the OAuth provider returns the user to your server, the plugin automatically redirects them to the intended callback URL.】

为了在代理服务器和主服务器之间共享 Cookie,它使用 URL 查询参数将加密的 Cookie 传递在 URL 中。这是安全的,因为 Cookie 是加密的,且只能由服务器解密。

【To share cookies between the proxy server and your main server it uses URL query parameters to pass the cookies encrypted in the URL. This is secure as the cookies are encrypted and can only be decrypted by the server.】

此插件需要跳过状态 Cookie 检查。这具有安全隐患,应仅在开发或预发布环境中使用。如果 baseURLproductionURL 相同,插件将不会代理请求。

选项

【Options】

currentURL: 应用的当前 URL 由插件自动确定。它首先检查客户端调用的请求 URL,然后检查常用托管提供商的基础 URL,最后回退到你的身份验证配置中的 baseURL。如果 URL 未正确推断,你可以在此处手动指定。

productionURL:如果此值与你的身份验证配置中的 baseURL 相匹配,请求将不会被代理。默认使用 BETTER_AUTH_URL 环境变量。

maxAge:加密 cookie 负载的最大时长(以秒为单位)。超过此时间的负载将被拒绝,以防止重放攻击。请将此值保持较短(例如 30-60 秒),以尽量减少潜在重放攻击的时机,同时仍允许正常的 OAuth 流程。默认值为 60 秒。

On this page