一次性令牌插件

一次性令牌(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】

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

要使用一次性令牌插件,请将其添加到你的认证配置中。

auth.ts
import { betterAuth } from "better-auth";
import { oneTimeToken } from "better-auth/plugins/one-time-token";

export const auth = betterAuth({
    plugins: [
      oneTimeToken()
    ]
    // ... other auth config
});

添加客户端插件

接下来,在你的认证客户端实例中包含一次性令牌客户端插件。

auth-client.ts
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.generateOneTimeTokenauthClient.oneTimeToken.generate 生成令牌

【Generate a token using auth.api.generateOneTimeToken or authClient.oneTimeToken.generate

GET
/one-time-token/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.verifyOneTimeTokenauthClient.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.】

POST
/one-time-token/verify
const { data, error } = await authClient.oneTimeToken.verify({    token: "some-token", // required});
PropDescriptionType
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: A custom token generator function that takes session object and a ctx as parameters.

  • storeToken:可选。此选项允许你配置令牌在数据库中的存储方式。

    • plain:令牌以明文形式存储。(默认)
    • hashed:令牌使用默认哈希算法进行哈希处理。
    • custom-hasher:一个自定义哈希函数,接收一个令牌并返回哈希后的令牌。

注意:这不会影响发送的令牌,仅会影响存储在你数据库中的令牌。

示例:

【Examples:】

No hashing (default)
oneTimeToken({
    storeToken: "plain"
})
built-in hasher
oneTimeToken({
    storeToken: "hashed"
})
custom hasher
oneTimeToken({
    storeToken: {
        type: "custom-hasher",
        hash: async (token) => {
            return myCustomHasher(token);
        }
    }
})

On this page