承载令牌认证

Bearer 插件允许使用 Bearer 令牌进行身份验证,作为浏览器 Cookie 的替代方式。它会拦截请求,在将请求转发到你的 API 之前,将 Bearer 令牌添加到 Authorization 头中。

【The Bearer plugin enables authentication using Bearer tokens as an alternative to browser cookies. It intercepts requests, adding the Bearer token to the Authorization header before forwarding them to your API.】

请谨慎使用;此方法仅适用于不支持 Cookie 或需要 Bearer 令牌进行身份验证的 API。若实现不当,可能会很容易导致安全漏洞。

安装 Bearer 插件

【Installing the Bearer Plugin】

将 Bearer 插件添加到你的身份验证设置中:

【Add the Bearer plugin to your authentication setup:】

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

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

如何使用承载令牌

【How to Use Bearer Tokens】

1. 获取 Bearer 令牌

【1. Obtain the Bearer Token】

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

【After a successful sign-in, you'll receive a session token in the response headers. Store this token securely (e.g., in localStorage):】

auth-client.ts
const { data } = await authClient.signIn.email({
    email: "user@example.com",
    password: "securepassword"
}, {
  onSuccess: (ctx)=>{
    const authToken = ctx.response.headers.get("set-auth-token") // get the token from the response headers
    // Store the token securely (e.g., in localStorage)
    localStorage.setItem("bearer_token", authToken);
  }
});

你也可以在你的认证客户端中全局设置这一项:

【You can also set this up globally in your auth client:】

auth-client.ts
export const authClient = createAuthClient({
    fetchOptions: {
        onSuccess: (ctx) => {
            const authToken = ctx.response.headers.get("set-auth-token") // get the token from the response headers
            // Store the token securely (e.g., in localStorage)
            if(authToken){
              localStorage.setItem("bearer_token", authToken);
            }
        }
    }
});

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

【You may want to clear the token based on the response status code or other conditions:】

2. 配置认证客户端

【2. Configure the Auth Client】

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

【Set up your auth client to include the Bearer token in all requests:】

auth-client.ts
export const authClient = createAuthClient({
    fetchOptions: {
        auth: {
           type:"Bearer",
           token: () => localStorage.getItem("bearer_token") || "" // get the token from localStorage
        }
    }
});

3. 发起已认证请求

【3. Make Authenticated Requests】

现在你可以进行经过身份验证的 API 调用:

【Now you can make authenticated API calls:】

auth-client.ts
// This request is automatically authenticated
const { data } = await authClient.listSessions();

4. 每次请求的令牌(可选)

【4. Per-Request Token (Optional)】

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

【You can also provide the token for individual requests:】

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

5. 在认证客户端之外使用承载令牌

【5. Using Bearer Tokens Outside the Auth Client】

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

【The Bearer token can be used to authenticate any request to your API, even when not using the auth client:】

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 函数对请求进行身份验证:

【On the server, you can authenticate requests using the auth.api.getSession function, as long as the Authorization Bearer token header is present in the request:】

server.ts
import { auth } from "@/auth";

export async function handler(req, res) {
  // Make sure `req.headers` contains the Authorization Bearer token header!
  const session = await auth.api.getSession({
    headers: req.headers
  });
  
  if (!session) {
    return res.status(401).json({ error: "Unauthorized" });
  }
  
  // Process authenticated request
  // ...
}

选项

【Options】

requireSignature(布尔值):是否要求令牌被签名。默认值:false

On this page