Bearer 令牌认证

使用 Bearer 令牌而非浏览器 cookie 来认证 API 请求

Bearer 插件支持使用 Bearer 令牌进行认证,作为浏览器 cookie 的替代方案。它会拦截请求,在转发到你的 API 之前,将 Bearer 令牌添加到 Authorization 头中。

请谨慎使用;该功能仅适用于不支持 cookie 或需要使用 Bearer 令牌进行认证的 API。不当的实现可能会导致安全漏洞。

安装 Bearer 插件

将 Bearer 插件添加到你的认证配置中:

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

export const auth = betterAuth({
    plugins: [bearer()]
});

如何使用 Bearer 令牌

1. 获取 Bearer 令牌

登录成功后,你将在响应头中收到一个会话令牌。请安全地存储该令牌(例如,存储到 localStorage):

import { authClient } from "@/lib/auth-client"

const { data } = await authClient.signIn.email({
    email: "user@example.com",
    password: "securepassword"
}, {
  onSuccess: (ctx)=>{
    const authToken = ctx.response.headers.get("set-auth-token") // 从响应头中获取令牌
    // 安全存储令牌(例如,存储到 localStorage)
    localStorage.setItem("bearer_token", authToken);
  }
});

你也可以在全局的认证客户端中设置该行为:

auth-client.ts
import { createAuthClient } from "better-auth/client"

export const authClient = createAuthClient({
    fetchOptions: {
        onSuccess: (ctx) => {
            const authToken = ctx.response.headers.get("set-auth-token") // 从响应头中获取令牌
            // 安全存储令牌(例如,存储到 localStorage)
            if(authToken){
              localStorage.setItem("bearer_token", authToken);
            }
        }
    }
});

你可能需要根据响应状态码或其他条件清除该令牌:

2. 配置认证客户端

设置你的认证客户端,在所有请求中包含 Bearer 令牌:

auth-client.ts
import { createAuthClient } from "better-auth/client"

export const authClient = createAuthClient({
    fetchOptions: {
        auth: {
           type:"Bearer",
           token: () => localStorage.getItem("bearer_token") || "" // 从 localStorage 获取令牌
        }
    }
});

3. 发起认证请求

现在你可以发起认证的 API 调用:

import { authClient } from "@/lib/auth-client"

// 该请求会自动携带认证信息
const { data } = await authClient.listSessions();

4. 单次请求使用令牌(可选)

你也可以为单独的请求提供令牌:

import { authClient } from "@/lib/auth-client"

const { data } = await authClient.listSessions({
    fetchOptions: {
        headers: {
            Authorization: `Bearer ${token}`
        }
    }
});

5. 在认证客户端外使用 Bearer 令牌

Bearer 令牌也可用来认证任何对你的 API 的请求,即使不使用认证客户端:

api-call.ts
const token = localStorage.getItem("bearer_token");

const response = await fetch("https://api.example.com/data", {
  headers: {
    Authorization: `Bearer ${token}`
  }
});

const data = await response.json();

在服务器端,只要请求中包含 Authorization Bearer 令牌头,即可使用 auth.api.getSession 函数进行认证:

session.ts
import { auth } from "@/lib/auth"

export async function handler(req, res) {
  // 确保 `req.headers` 中包含 Authorization Bearer 令牌头!
  const session = await auth.api.getSession({
    headers: req.headers
  });
  
  if (!session) {
    return res.status(401).json({ error: "Unauthorized" });
  }
  
  // 处理认证请求
  // ...
}

选项

requireSignature (boolean):是否要求令牌必须经签名。默认值:false