一次性令牌插件
一次性令牌(OTT)插件提供生成和验证安全、一次性使用会话令牌的功能。这些令牌通常用于跨域认证。
🌐 The One-Time Token (OTT) plugin provides functionality to generate and verify secure, single-use session tokens. These are commonly used for across domains authentication.
安装
🌐 Installation
将插件添加到你的认证配置
要使用一次性令牌插件,请将其添加到你的认证配置中。
import { betterAuth } from "better-auth";
import { oneTimeToken } from "better-auth/plugins/one-time-token";
export const auth = betterAuth({
plugins: [
oneTimeToken()
]
// ... other auth config
});添加客户端插件
接下来,在你的认证客户端实例中包含一次性令牌客户端插件。
import { createAuthClient } from "better-auth/client"
import { oneTimeTokenClient } from "better-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [
oneTimeTokenClient()
]
})用法
🌐 Usage
1. 生成令牌
🌐 1. Generate a Token
使用 auth.api.generateOneTimeToken 或 authClient.oneTimeToken.generate 生成令牌
🌐 Generate a token using auth.api.generateOneTimeToken or authClient.oneTimeToken.generate
const { data, error } = await authClient.oneTimeToken.generate();这将返回一个附加到当前会话的 token,可用于验证一次性令牌。默认情况下,令牌将在 3 分钟后过期。
🌐 This will return a token that is attached to the current session which can be used to verify the one-time token. By default, the token will expire in 3 minutes.
2. 验证令牌
🌐 2. Verify the Token
当用户点击链接或提交令牌时,在另一个 API 路由中使用 auth.api.verifyOneTimeToken 或 authClient.oneTimeToken.verify 方法来验证它。
🌐 When the user clicks the link or submits the token, use the auth.api.verifyOneTimeToken or authClient.oneTimeToken.verify method in another API route to validate it.
const { data, error } = await authClient.oneTimeToken.verify({ token: "some-token", // required});| Prop | Description | Type |
|---|---|---|
token | The token to verify. | string |
这将返回附加到令牌的会话。
🌐 This will return the session that was attached to the token.
选项
🌐 Options
在添加 oneTimeToken 插件时可以配置这些选项:
🌐 These options can be configured when adding the oneTimeToken plugin:
disableClientRequest(布尔值):可选。如果为true,令牌将仅在服务器端生成。默认值:false。expiresIn(数字):可选。令牌有效的时长,单位为分钟。默认值:3。
oneTimeToken({
expiresIn: 10 // 10 minutes
})generateToken:一个自定义令牌生成函数,接收session对象和ctx作为参数。storeToken:可选。此选项允许你配置令牌在数据库中的存储方式。plain:令牌以明文形式存储。(默认)hashed:令牌使用默认哈希算法进行哈希处理。custom-hasher:一个自定义哈希函数,接收一个令牌并返回哈希后的令牌。
注意:这不会影响发送的令牌,仅会影响存储在你数据库中的令牌。
示例:
🌐 Examples:
oneTimeToken({
storeToken: "plain"
})oneTimeToken({
storeToken: "hashed"
})oneTimeToken({
storeToken: {
type: "custom-hasher",
hash: async (token) => {
return myCustomHasher(token);
}
}
})