文档›指南›Authenticate users (SDK) 使用 JavaScript SDK 对用户进行身份验证
aura.auth的日常流程,以及针对正在运行的堆栈观察到的每个调用的行为。
11分钟 读取·级别 中间·修改于 2026年10月12日
该英文文本是根据法文原文自动生成的,尚未经过审查。
自此翻译以来,英文来源已发生变化。某些信息可能已过时。
该页面已自动翻译。英文版具有权威性。
auth.tstypescript
import { createClient, isMfaChallenge } from '@aurabase/aurabase-js'
const aura = createClient(process.env.AURA_URL!, process.env.AURA_ANON_KEY!)
// 创建帐户
const { data, error } = await aura.auth.signUp({ email: 'ada@example.com', password: 'a-long-passphrase' })
// 登录
const login = await aura.auth.signInWithPassword({ email: 'ada@example.com', password: 'a-long-passphrase' })
if (login.error) return showError(login.error.message)
if (login.data && isMfaChallenge(login.data)) return askForTotpCode(login.data.mfa_token)
// 否则会话现已存在
两个调用返回相同的形状。成功后, data 会保存 access_token、 refresh_token、 expires_in (900 秒)和 user,并且客户端会为您存储会话。下一个请求已通过身份验证。
signUp 的作用取决于您的项目设置。在我们的测试项目中,它使用 email_verified: false立即让用户登录,并且项目可能需要首先确认。
如观察到的,您应该处理的故障:
| 致电 | 错误 |
|---|
| 密码错误 | 401、 code: 'invalid_credentials'、“标识符无效” |
| 链接或代码无效或过期 | 401, code: 'invalid_otp' |
| 当项目不允许时匿名登录 | 403, FORBIDDEN |
signInAnonymously() 创建一个没有电子邮件地址的用户,但在新项目中,禁用 并返回 403,直到您在项目的身份验证设置中启用它。
session.tstypescript
const { data: { session } } = await aura.auth.getSession() // 无网络调用:读取存储
const { data: user } = await aura.auth.getUser() // 询问服务器
const { data: { subscription } } = aura.auth.onAuthStateChange(({ event, user }) => {
// 事件:'INITIAL_SESSION' | 'SIGNED_IN'| 'TOKEN_REFRESHED'| 'USER_UPDATED'| 'SIGNED_OUT'| 'MFA_挑战'
})
subscription.unsubscribe()
实际运行会产生以下序列: INITIAL_SESSION、 SIGNED_IN (注册)、 SIGNED_IN (登录)、 USER_UPDATED、 TOKEN_REFRESHED、 SIGNED_OUT。
- 客户端在访问令牌过期之前刷新访问令牌。调用
aura.auth.refreshSession() 强制执行。
getSession() 是本地的且快速:使用它进行渲染。当您需要服务器的用户当前视图时,请使用 getUser()。
- 要将会话从其他地方(cookie、服务器)传递给客户端,请使用
setSession(accessToken, refreshToken)。无效的对将被拒绝并保留先前的会话。
- 对于服务器端渲染,请参阅 Next.js App Router 和 SSR。
profile.tstypescript
// 元数据:将其传递到“data”中
await aura.auth.updateUser({ data: { theme: 'dark', plan: 'free' } })
// → user.user_metadata 是 { plan: 'free', theme: 'dark' },并且 getUser() 返回相同的
// 更改电子邮件:地址尚未更改
await aura.auth.updateUser({ email: 'new@example.com' })
// 确认链接将转到新地址。在使用之前,user.email 会保留旧值。
// 确认:aura.auth.verifyOtp({ type: 'email_change', token })
// 更改密码
await aura.auth.updatePassword('a-new-long-passphrase', 'a-long-passphrase')
更改密码使您退出
当密码更改时,服务器将撤销所有会话。 updatePassword 清除本地会话并发出 SIGNED_OUT:使用新密码再次登录。在实际运行中,getSession() 在调用后立即为空,并且使用新密码登录有效。
忘记密码:aura.auth.resetPasswordForEmail({ email }) 发送重置电子邮件。然后用户使用 verifyOtp({ type: 'recovery', token, password })完成它。
删除帐户:aura.auth.deleteUser(password) 询问当前密码,删除帐户并清除本地会话。
passwordless.tstypescript
// 通过电子邮件的神奇链接
await aura.auth.signInWithMagicLink({ email })
// → { message: "如果电子邮件存在,请与特使联系" }
// 无论账户存在与否,答案都是一样的:不会泄露账户。
// 一次性代码
await aura.auth.signInWithEmailOtp(email)
await aura.auth.signInWithSmsOtp(phone)
await aura.auth.verifyOtp({ type: 'email', email, code }) // 还有:“短信”、“magiclink”、“注册”、“恢复”、“email_change”
// OAuth:提供者是第一个参数,一个字符串
const { data } = await aura.auth.signInWithOAuth('google', { redirectTo: 'https://app.example.com/callback' })
window.location.href = data!.url
signInWithOAuth 返回要打开的URL;它不会自行导航。必须在项目中启用并配置提供程序,否则起始 URL 会返回 PROVIDER_NOT_CONFIGURED。
不是supabase-js形式
signInWithOAuth({ provider: 'google' }) 返回错误 invalid_provider。将提供者作为第一个参数传递。
重定向回来后,客户端自行从 URL 读取会话 (detectSessionInUrl)。对于 PKCE 流程,传递 flowType: 'pkce',保留默认的持久存储,客户端会为您交换代码。
使用 linkIdentity(provider)将第二个提供商链接到登录帐户,使用 listIdentities() 列出它们,并使用 unlinkIdentity(identityId)删除一个。
mfa.tstypescript
// 1. Enrol:显示根据otpauth_url构建的二维码
const { data: enrol } = await aura.auth.mfaEnroll() // → { 秘密,otpauth_url }
// 2. 使用身份验证器应用程序中的第一个代码进行确认:您会收到恢复代码
const { data: confirm } = await aura.auth.mfaVerifySetup(codeFromApp) // → { 恢复代码:[...] }
// 3. 从现在开始,登录返回的是挑战而不是会话
const login = await aura.auth.signInWithPassword({ email, password })
if (login.data && isMfaChallenge(login.data)) {
await aura.auth.mfaVerify({ mfa_token: login.data.mfa_token, code: codeFromApp })
}
mfaUnenroll(password) 将其关闭,并且 regenerateRecoveryCodes(code) 发出新的恢复代码。质询会发出 MFA_CHALLENGE 并且在 mfaVerify 成功之前不会存储任何会话。
devices.tstypescript
const { data } = await aura.auth.listSessions()
// [{ id、device_info、ip_address、created_at、expires_at、last_used_at、is_current }、...]
await aura.auth.revokeSession(sessionId) // 注销一台设备
await aura.auth.revokeAllSessions() // 在所有地方都注销,包括这个
await aura.auth.signOut() // 仅此设备
is_current 标记您正在使用的会话。 当服务器上有刷新令牌时, signOut 会撤销刷新令牌,清除本地会话并发出 SIGNED_OUT。
用户管理需要 service_role 密钥。它仅在服务器上可用:在浏览器中读取 aura.authAdmin 会引发错误。
server/users.tstypescript
import { createAdminClient } from '@aurabase/aurabase-js'
const admin = createAdminClient(process.env.AURA_URL!, process.env.AURA_SERVICE_ROLE_KEY!)
const { data: users } = await admin.authAdmin.listUsers({ limit: 20, search: 'ada' })
const { data: created } = await admin.authAdmin.createUser({ email: 'bob@example.com', password: 'a-long-passphrase', email_verified: true })
await admin.authAdmin.banUser(created!.id)
await admin.authAdmin.unbanUser(created!.id)
const { data: link } = await admin.authAdmin.generateLink(created!.id, 'magic') // → { 链接、令牌 }
await admin.authAdmin.deleteUser(created!.id)
const { data: stats } = await admin.authAdmin.getUserStats() // → { 总计、已验证、已禁止、mfa_enabled、new_7d }
generateLink 接受 'magic'、 'recovery' 或 'invite'。管理客户端还管理项目的身份验证设置(getSettings、 updateSettings)、电子邮件模板、每个用户的会话以及审核日志(getAuditLog)。每个方法都列在 身份验证参考中。