多会话
多会话插件允许用户在同一浏览器中保持多个不同账户的活动会话。对于需要用户在多个账户之间切换而无需注销的应用,这个插件非常有用。
【The multi-session plugin allows users to maintain multiple active sessions across different accounts in the same browser. This plugin is useful for applications that require users to switch between multiple accounts without logging out.】
安装
【Installation】
将插件添加到你的 auth 配置中
【Add the plugin to your auth config】
import { betterAuth } from "better-auth"
import { multiSession } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
multiSession(),
]
})Add the client Plugin
添加客户端插件,并指定如果用户需要验证第二因素时应重定向到的位置
import { createAuthClient } from "better-auth/client"
import { multiSessionClient } from "better-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [
multiSessionClient()
]
})用法
【Usage】
每当用户登录时,插件会向浏览器添加额外的 Cookie。该 Cookie 将用于在不同账户之间维持多个会话。
【Whenever a user logs in, the plugin will add additional cookie to the browser. This cookie will be used to maintain multiple sessions across different accounts. 】
列出所有设备会话
【List all device sessions】
要列出当前用户的所有活动会话,你可以调用 listDeviceSessions 方法。
【To list all active sessions for the current user, you can call the listDeviceSessions method.】
const { data, error } = await authClient.multiSession.listDeviceSessions();设置活动会话
【Set active session】
要设置活动会话,你可以调用 setActive 方法。
【To set the active session, you can call the setActive method.】
const { data, error } = await authClient.multiSession.setActive({ sessionToken: "some-session-token", // required});| Prop | Description | Type |
|---|---|---|
sessionToken | The session token to set as active. | string |
撤销会话
【Revoke a session】
要撤销会话,你可以调用 revoke 方法。
【To revoke a session, you can call the revoke method.】
const { data, error } = await authClient.multiSession.revoke({ sessionToken: "some-session-token", // required});| Prop | Description | Type |
|---|---|---|
sessionToken | The session token to revoke. | string |
登出并撤销所有会话
【Signout and Revoke all sessions】
当用户登出时,该插件将撤销用户的所有活动会话。你可以通过调用现有的 signOut 方法来执行此操作,该方法会自动处理撤销所有会话。
【When a user logs out, the plugin will revoke all active sessions for the user. You can do this by calling the existing signOut method, which handles revoking all sessions automatically.】
最大会话数
【Max Sessions】
你可以通过向插件传递 maximumSessions 选项来指定用户可以拥有的最大会话数。默认情况下,插件每个设备允许 5 个会话。
【You can specify the maximum number of sessions a user can have by passing the maximumSessions option to the plugin. By default, the plugin allows 5 sessions per device.】
import { betterAuth } from "better-auth"
export const auth = betterAuth({
plugins: [
multiSession({
maximumSessions: 3
})
]
})