Bearer令牌认证

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中):

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

你也可以在auth客户端中全局设置此功能:

auth-client.ts
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. 配置Auth客户端

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

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

3. 发送认证请求

现在你可以进行认证的API调用:

auth-client.ts
// 此请求会自动进行认证
const { data } = await authClient.listSessions();

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

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

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

5. 在Auth客户端之外使用Bearer令牌

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

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函数来认证请求:

server.ts
import { auth } from "@/auth";
 
export async function handler(req, res) {
  const session = await auth.api.getSession({
    headers: req.headers
  });
  
  if (!session) {
    return res.status(401).json({ error: "Unauthorized" });
  }
  
  // 处理已认证的请求
  // ...
}

选项

requireSignature (boolean): 要求令牌被签名。默认值:false

On this page