安全

本页面包含有关 Better Auth 安全功能的信息。

【This page contains information about security features of Better Auth.】

密码哈希

【Password Hashing】

Better Auth 默认使用 scrypt 算法来哈希密码。该算法设计为内存密集型和 CPU 密集型,从而抵御暴力破解攻击。你可以通过在配置中设置 password 选项来自定义密码哈希函数。此选项应包括一个用于哈希密码的 hash 函数和一个用于验证密码的 verify 函数。

【Better Auth uses the scrypt algorithm to hash passwords by default. This algorithm is designed to be memory-hard and CPU-intensive, making it resistant to brute-force attacks. You can customize the password hashing function by setting the password option in the configuration. This option should include a hash function to hash passwords and a verify function to verify them.】

会话管理

【Session Management】

会话过期

【Session Expiration】

Better Auth 使用安全的会话管理来保护用户数据。会话存储在数据库中,或者在配置了次级存储时存储在次级存储中,以防止未经授权的访问。默认情况下,会话在 7 天后过期,但你可以在配置中自定义此值。此外,每次使用会话时,如果达到 updateAge 阈值,会延长过期日期,默认设置为 1 天。

【Better Auth uses secure session management to protect user data. Sessions are stored in the database or a secondary storage, if configured, to prevent unauthorized access. By default, sessions expire after 7 days, but you can customize this value in the configuration. Additionally, each time a session is used, if it reaches the updateAge threshold, the expiration date is extended, which by default is set to 1 day.】

会话撤销

【Session Revocation】

Better Auth 允许你撤销会话以增强安全性。当会话被撤销时,用户将被登出,无法再访问应用。已登录的用户也可以撤销自己的会话,以从不同的设备或浏览器登出。

【Better Auth allows you to revoke sessions to enhance security. When a session is revoked, the user is logged out and can no longer access the application. A logged in user can also revoke their own sessions to log out from different devices or browsers.】

有关更多详细信息,请参阅会话管理

【See the session management for more details.】

CSRF 保护

【CSRF Protection】

Better Auth 包含多种防护措施,以防止跨站请求伪造(CSRF)攻击:

【Better Auth includes multiple safeguards to prevent Cross-Site Request Forgery (CSRF) attacks:】

  1. 避免简单请求 查看 避免简单请求 了解更多详情。Better Auth 仅允许带有非简单头部或 Content-Typeapplication/json 的请求。

  2. 来源验证 每个请求的 Origin 头都会被验证,以确认其来源是你的应用或其他明确的受信任来源。来自不受信任来源的请求将被拒绝。默认情况下,Better Auth 会信任你应用的基础 URL,但你可以通过 trustedOrigins 配置选项指定额外的受信任来源。

  3. 安全的 Cookie 设置 会话 Cookie 默认使用 SameSite=Lax 属性,这可以防止浏览器在大多数跨站请求中发送 Cookie。你可以使用 defaultCookieAttributes 选项覆盖此行为。

  4. 首次登录 CSRF 的 Fetch 元数据保护 Better Auth 还使用 Fetch 元数据头Sec-Fetch-SiteSec-Fetch-ModeSec-Fetch-Dest)来为首次登录场景提供额外的 CSRF 保护,此时客户端尚未拥有任何 Cookie。

    此保护适用于登录和注册电子邮件路径,这些路径接受表单提交(简单请求),以支持渐进增强模式。

    当收到 没有 任何 Cookie 的登录或注册请求时:

    • 如果浏览器指示跨站导航(例如:Sec-Fetch-Site: cross-siteSec-Fetch-Mode: navigate),Better Auth 会将该请求阻止,因为它可能是登录 CSRF 攻击。
    • 如果请求是同源同站点,Better Auth 仍会根据你配置的 trustedOrigins 验证 Origin/Referer,使用现有的来源验证逻辑。
    • 如果客户端没有发送 Fetch Metadata 头(旧版浏览器、某些移动 WebView、非浏览器客户端),Better Auth 会回退到其以前的行为,仅在存在 Cookie 时执行来源验证,以保持向后兼容性。

    该机制使现代浏览器在首次登录防护 CSRF 攻击时获得更强的保护 无需 CSRF 令牌或客户端 JavaScript,并且能够与渐进增强模式无缝配合。

    非浏览器的 HTTP 客户端(移动应用、服务器间通信)在发送包含 cookie 的请求时,应适当地设置 OriginReferer 头。这可以确保无论是否支持 Fetch Metadata,都能正确进行 CSRF 验证。

  5. GET 请求不应有修改操作(附加安全保障措施) GET 请求通常被认为是只读的,不应改变应用的状态。在必须通过 GET 请求执行修改操作的情况——例如在 OAuth 回调期间——Better Auth 会采取额外的安全措施,包括验证 noncestate 参数,以确保请求的真实性。

禁用安全检查

【Disabling Security Checks】

更好的认证提供了两个不同的选项来禁用安全检查。这些选项控制着安全的不同方面:

【Better Auth provides two separate options to disable security checks. These options control different aspects of security:】

disableCSRFCheck

禁用所有 CSRF 保护,包括:

  • 当存在 Cookie 时验证 Origin 头
  • Fetch 元数据检查(Sec-Fetch-SiteSec-Fetch-ModeSec-Fetch-Dest
  • 针对首次登录场景的跨站导航阻止

【Disables all CSRF protection, including:

  • Origin header validation when cookies are present
  • Fetch Metadata checks (Sec-Fetch-Site, Sec-Fetch-Mode, Sec-Fetch-Dest)
  • Cross-site navigation blocking for first-login scenarios】
{
  advanced: {
    disableCSRFCheck: true
  }
}

禁用 CSRF 检查允许来自任何来源的请求使用 Cookie 并代表用户执行操作。这会使你的应用容易受到 CSRF 攻击。

disableOriginCheck

禁用针对 trustedOriginsURL 验证,包括:

  • callbackURL 验证
  • redirectTo 验证
  • errorCallbackURL 验证
  • newUserCallbackURL 验证

【Disables URL validation against trustedOrigins, including:

  • callbackURL validation
  • redirectTo validation
  • errorCallbackURL validation
  • newUserCallbackURL validation】
{
  advanced: {
    disableOriginCheck: true
  }
}

禁用来源检查允许在重定向和回调中使用任何 URL。这会使你的应用面临开放重定向漏洞的风险。

为了向后兼容,disableOriginCheck: true 同时也会禁用 CSRF 防护。如果你只想禁用 URL 验证而不影响 CSRF 防护,目前无法做到——使用此选项时,两项检查会同时被禁用。

摘要

【Summary】

选项它禁用了什么
'disableCSRFCheck'仅限CSRF保护(源头验证,获取元数据检查)
'disableOriginCheck'URL 验证和 CSRF 保护(用于向后兼容)

OAuth 状态和 PKCE

【OAuth State and PKCE】

为了保障 OAuth 流程的安全,Better Auth 会将 OAuth 状态和 PKCE(用于代码交换的证明密钥)存储在数据库中。OAuth 状态有助于防止 CSRF 攻击,而 PKCE 则可防止代码注入威胁。一旦 OAuth 流程完成,这些值将从数据库中删除。

【To secure OAuth flows, Better Auth stores the OAuth state and PKCE (Proof Key for Code Exchange) in the database. The state helps prevent CSRF attacks, while PKCE protects against code injection threats. Once the OAuth process completes, these values are removed from the database.】

Cookies

当基础 URL 使用 https 时,Better Auth 会默认分配安全 cookie。这些安全 cookie 是加密的,并且仅通过安全连接发送,从而增加了一层保护。它们还默认将 sameSite 属性设置为 lax,以防止跨站请求伪造攻击。同时启用 httpOnly 属性,以防止客户端 JavaScript 访问该 cookie。

【Better Auth assigns secure cookies by default when the base URL uses https. These secure cookies are encrypted and only sent over secure connections, adding an extra layer of protection. They are also set with the sameSite attribute to lax by default to prevent cross-site request forgery attacks. And the httpOnly attribute is enabled to prevent client-side JavaScript from accessing the cookie. 】

对于跨子域的 Cookie,你可以在配置中设置 crossSubDomainCookies 选项。此选项允许 Cookie 在子域之间共享,从而实现多个子域的无缝认证。

【For Cross-Subdomain Cookies, you can set the crossSubDomainCookies option in the configuration. This option allows cookies to be shared across subdomains, enabling seamless authentication across multiple subdomains.】

自定义 Cookies

【Customizing Cookies】

你可以自定义 cookie 名称,以尽量减少指纹攻击的风险,并根据需要设置特定的 cookie 选项以获得更多控制。有关更多信息,请参阅 cookie 选项

【You can customize cookie names to minimize the risk of fingerprinting attacks and set specific cookie options as needed for additional control. For more information, refer to the cookie options.】

插件还可以设置自定义的 Cookie 选项,以符合特定的安全需求。如果你在非浏览器环境中使用 Better Auth,插件也提供了在这些环境中安全管理 Cookie 的方法。

【Plugins can also set custom cookie options to align with specific security needs. If you're using Better Auth in non-browser environments, plugins offer ways to manage cookies securely in those contexts as well.】

速率限制

【Rate Limiting】

Better Auth 包含内置的速率限制,以防止暴力破解攻击。默认情况下,速率限制适用于所有路由,对于某些特定路由,则会根据潜在风险采取更严格的限制。

【Better Auth includes built-in rate limiting to safeguard against brute-force attacks. Rate limits are applied across all routes by default, with specific routes subject to stricter limits based on potential risk.】

IP 地址头

【IP Address Headers】

Better Auth 使用客户端 IP 地址进行速率限制和安全监控。默认情况下,它会从标准的 X-Forwarded-For 头部读取 IP 地址。不过,你可以配置特定的可信头部,以确保准确检测 IP 地址并防止 IP 欺骗攻击。

【Better Auth uses client IP addresses for rate limiting and security monitoring. By default, it reads the IP address from the standard X-Forwarded-For header. However, you can configure a specific trusted header to ensure accurate IP address detection and prevent IP spoofing attacks.】

你可以在 Better Auth 配置中设置 IP 地址头:

【You can configure the IP address header in your Better Auth configuration:】

{
  advanced: {
    ipAddress: {
      ipAddressHeaders: ['cf-connecting-ip'] // or any other custom header
    }
  }
}

这确保了 Better Auth 只接受来自你受信任代理头部的 IP 地址,从而使攻击者通过伪造头部绕过速率限制或其他基于 IP 的安全措施变得更加困难。

【This ensures that Better Auth only accepts IP addresses from your trusted proxy's header, making it more difficult for attackers to bypass rate limiting or other IP-based security measures by spoofing headers.】

重要

  • 在设置自定义 IP 地址头时,请确保你的代理或负载均衡器已正确配置以设置此头部,并且终端用户不能直接设置它。
  • 在开发/测试环境中,如果无法从头信息中获取 IP,则使用 127.0.0.1 作为备用。

受信任的来源

【Trusted Origins】

受信任的来源可以防止 CSRF 攻击并阻止开放重定向。你可以在 trustedOrigins 配置选项中设置受信任来源列表。来自不在此列表中的来源的请求会被自动阻止。

【Trusted origins prevent CSRF attacks and block open redirects. You can set a list of trusted origins in the trustedOrigins configuration option. Requests from origins not on this list are automatically blocked.】

基本用法

【Basic Usage】

最基本的用法是指定确切的来源:

【The most basic usage is to specify exact origins:】

{
  trustedOrigins: [
    "https://example.com",
    "https://app.example.com",
    "http://localhost:3000"
  ]
}

通配符起源

【Wildcard Origins】

Better Auth 支持受信任来源中的通配符模式,这允许你通过一个条目信任多个子域名:

【Better Auth supports wildcard patterns in trusted origins, which allows you to trust multiple subdomains with a single entry:】

{
  trustedOrigins: [
    "*.example.com",             // Trust all subdomains of example.com (any protocol)
    "https://*.example.com",     // Trust only HTTPS subdomains of example.com
    "http://*.dev.example.com"   // Trust all HTTP subdomains of dev.example.com
  ]
}

特定协议的通配符

【Protocol-specific wildcards】

在使用带有协议前缀的通配符模式(例如 https://)时:

  • 协议必须完全匹配
  • 域名可以在 * 的位置使用任何子域名
  • 即使域名匹配,使用不同协议的请求也会被拒绝

【When using a wildcard pattern with a protocol prefix (like https://):

  • The protocol must match exactly
  • The domain can have any subdomain in place of the *
  • Requests using a different protocol will be rejected, even if the domain matches】

协议无关的通配符

【Protocol-agnostic wildcards】

当使用没有协议前缀的通配符模式(如 *.example.com)时:

  • 将接受任何协议(http、https 等)
  • 域名必须匹配通配符模式

【When using a wildcard pattern without a protocol prefix (like *.example.com):

  • Any protocol (http, https, etc.) will be accepted
  • The domain must match the wildcard pattern】

自定义方案

【Custom Schemes】

受信任的来源也支持移动应用和浏览器扩展的自定义方案:

【Trusted origins also support custom schemes for mobile apps and browser extensions:】

{
  trustedOrigins: [
    "myapp://",                               // Mobile app scheme
    "chrome-extension://YOUR_EXTENSION_ID",   // Browser extension
    "exp://**",                               // Trust all Expo development URLs
    "exp://10.0.0.*:*/**",                    // Trust 10.0.0.x IP range with any port
  ]
}

动态源列表

【Dynamic origin list】

你也可以通过提供一个返回它的函数来动态设置受信任的来源列表:

【You can also dynamically set the list of trusted origins by providing a function that returns it:】

{
  trustedOrigins: async (request) => {
    const trustedOrigins = await queryTrustedDomains();
    return trustedOrigins;
  }
}

重要:此功能将针对每个传入请求调用,因此如果你决定动态获取受信任域名列表,请务必小心。

报告漏洞

【Reporting Vulnerabilities】

如果你在 Better Auth 中发现安全漏洞,请通过 security@better-auth.com 向我们报告。我们会及时处理所有报告,并对经过验证的发现给予鸣谢。

【If you discover a security vulnerability in Better Auth, please report it to us at security@better-auth.com. We address all reports promptly, and credits will be given for validated discoveries.】