# Bearer 令牌认证 (/docs/plugins/bearer)

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



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

<Callout type="warn">
  请谨慎使用；该功能仅适用于不支持 cookie 或需要使用 Bearer 令牌进行认证的 API。不当的实现可能会导致安全漏洞。
</Callout>

## 安装 Bearer 插件 [#安装-bearer-插件]

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

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

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

## 如何使用 Bearer 令牌 [#如何使用-bearer-令牌]

### 1. 获取 Bearer 令牌 [#1-获取-bearer-令牌]

登录成功后，你将在响应头中收到一个会话令牌。请安全地存储该令牌（例如，存储到 `localStorage`）：

```ts
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);
  }
});
```

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

```ts title="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);
            }
        }
    }
});
```

你可以根据响应状态码或其他条件来清除令牌：

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

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

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

### 3. 发起认证请求 [#3-发起认证请求]

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

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

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

### 4. 单次请求使用令牌（可选） [#4-单次请求使用令牌可选]

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

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

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

### 5. 在认证客户端外使用 Bearer 令牌 [#5-在认证客户端外使用-bearer-令牌]

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

```ts title="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();
```

在服务端，你可以使用 `auth.api.getSession` 函数来认证请求，
只要请求中包含 Authorization Bearer 令牌头：

```ts title="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**（布尔值）：是否需要对令牌进行签名。默认值：`false`。

