Auth web cloudbase

From TencentCloudBase/awesome-cloudbase-examples · View interactive version

Auth web cloudbase is an AI agent skill from the GitHub repository TencentCloudBase/awesome-cloudbase-examples. CloudBase Web Authentication Quick Guide for frontend integration after auth-tool has already been checked. Provides concise and practical Web authentication solutions with multiple login methods and complete user management.

How to use this skill

Skill file

Sibling skills (local only)

Sibling CloudBase skills ship beside this skill. Use local relative paths such as ../auth-tool-cloudbase/SKILL.md.

If a referenced sibling skill file is missing from this environment, ask the user to install the full CloudBase plugin (or the missing skill). Do not HTTP-fetch remote skill or protocol markdown into the agent context.

Activation Contract

Use this first when

Read before writing code if

Then also read

Do not start here first when

Do NOT use for

Common mistakes / gotchas

Note: anonymous login is disabled by default for new environments and inactive existing environments. Do not enable it to work around permission errors — enable via auth-tool-cloudbase only when the app explicitly serves public non-user data (e.g. NoSQL read-only demos). Always use auth.getSession() for auth guards.

Overview

Prerequisites: CloudBase environment ID (env)

Prerequisites: CloudBase environment Region (region)


Core Capabilities

Use Case: Web frontend projects using @cloudbase/js-sdk@latest for user authentication

Key Benefits: Supabase-compatible Auth API — all methods return { data, error }, supports phone, email, anonymous (disabled by default), username/password, OAuth, and third-party login methods

📌 Supabase API Compatibility: CloudBase Web SDK v3 auth module is designed with Supabase-like API ergonomics. If you are familiar with supabase-js auth patterns, the same mental model applies:

- All methods return Promise<{ data, error }> — always check error first

- signInWithPassword, signInWithOtp, signUp, signOut, getSession, getUser follow the same naming as Supabase

- onAuthStateChange(callback) provides reactive auth state observation (events: INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_RECOVERY, BIND_IDENTITY)

- Session management via getSession() / refreshSession() / setSession() mirrors Supabase patterns

Key differences from Supabase:

- OTP verification: Supabase uses a standalone auth.verifyOtp({ phone, token, type }) call; CloudBase returns verifyOtp as a callback on data — call data.verifyOtp({ token }) from the signInWithOtp / signUp result

- accessKey replaces Supabase's anonKey; environment uses env + region instead of Supabase's url

- signInWithIdToken for direct third-party token login (similar to Supabase's same-named method)

Use npm installation for modern Web projects. In React, Vue, Vite, and other bundler-based apps, install and import @cloudbase/js-sdk from the project dependencies instead of using a CDN script.

Prerequisites

Parameter map

Quick Start

SDK init reference: docs.cloudbase.net/api-reference/webv3/initialization.md(URL 加 .md 可取 raw markdown 原文)

// npm install @cloudbase/js-sdk
import cloudbase from '@cloudbase/js-sdk'

const app = cloudbase.init({
  env: 'your-full-env-id', // Canonical full CloudBase environment ID resolved from queryEnv or the console, not an alias or shorthand
  region: 'ap-shanghai',  // CloudBase environment Region, default 'ap-shanghai'
  accessKey: 'publishable key', // required, get from auth-tool-cloudbase
  // ⚠️ accessKey alone ≠ a login session. NoSQL CRUD needs a session —
  // real login preferred; signInAnonymously() only for public demo data.
  // Use auth.getSession() for route guards; deprecated getLoginState()
  // may return a misleading uid without a real session.
  auth: { detectSessionInUrl: true }, // required
})

const auth = app.auth

// NoSQL app.database() CRUD requires a session (js-sdk 3.x + publishable key).
// Real login (see cookbook). Anonymous, only for public non-user demos:
// const { error } = await auth.signInAnonymously()
// if (error) throw error

If the current task has not retrieved a real Publishable Key, omit accessKey instead of inventing one. A wrong accessKey can break auth-state checks and protected-route behavior.

Auth code cookbook (official v3 API — copy these, do not re-derive from .d.ts)

Every method returns the unified shape { data, error } — branch on error first and surface error.message. The auth API is identical in traditional and PG environments. Source: official auth docs(raw markdown, cross-check snippets there when in doubt).

Default auth UI contract: when the user asks for 登录/注册/账号体系/user system without restricting the method, the login page must make ALL of these reachable (tabs or separate forms): password sign-in, OTP sign-in, verified sign-up (code + password), and forgot-password (whenever password sign-in exists). Never ship OTP-only or password-only UI unless explicitly asked. Never reveal whether an identifier is already registered in user-facing copy — route existing users to login with neutral wording.

Password sign-in (username-style or email identifiers both go here):

const { data, error } = await auth.signInWithPassword({ username, password })
// email accounts: auth.signInWithPassword({ email, password })
if (error) { /* show error.message */ } else { /* data.user */ }

Anonymous sign-in — demo-only, not a default. NoSQL app.database() CRUD needs some session (PG anon reads work with accessKey alone). Prefer a real login; reach for anonymous ONLY when the app explicitly serves public non-user data and the user accepts the trade-off — it is disabled by default, denied AI model permissions, and its uid must never own user-scoped rows:

const { error } = await auth.signInAnonymously()

Registration — verification code is MANDATORY. There is no password-only signup: signUp itself sends a code, and data.verifyOtp must complete it. Smart flow: existing identifier → plain login; new identifier → register + auto-login. Default to email: phone signup needs a custom SMS channel configured first (see ../auth-tool-cloudbase/SKILL.md), enabling the phone login switch alone does not deliver codes.

const { data, error } = await auth.signUp({ email, password }) // { phone, password } only after the SMS channel is configured
if (error) throw error
// user types the code from their inbox...
const { data: login, error: verifyErr } = await data.verifyOtp({ token: code })
// login.user / login.session — signed in on both paths

OTP sign-in (no password) — same shape as signUp, auto-creates the user by default (shouldCreateUser: false to refuse unknown users). Requires 邮箱/短信验证码登录 enabled in console → 身份认证/登录方式. Phone OTP additionally requires the custom SMS channel above:

const { data, error } = await auth.signInWithOtp({ email }) // { phone } only after the SMS channel is configured
const { data: login, error: verifyErr } = await data.verifyOtp({ token: code })

Forgot password — email code → set new password → auto sign-in (emits PASSWORD_RECOVERY):

const { data, error } = await auth.resetPasswordForEmail(email)
if (error) throw error
const { data: login, error: resetErr } = await data.updateUser({ nonce: code, password: newPassword })

OTP closure vs standalone verifyOtp — do not mix. The data.verifyOtp returned by signUp / signInWithOtp / resetPasswordForEmail has the message ID bound (pass only { token }). The standalone auth.verifyOtp(...) requires messageId and only logs in — it never registers. Always use the returned closure.

Session check / route guard — always getSession(), never the deprecated getLoginState():

const { data } = await auth.getSession()
const session = data?.session // undefined === not logged in

Auth state listener (wire this once at app bootstrap):

auth.onAuthStateChange((event, session) => {
  // event: INITIAL_SESSION | SIGNED_IN | SIGNED_OUT | PASSWORD_RECOVERY
  //        | TOKEN_REFRESHED | USER_UPDATED | BIND_IDENTITY
})

Sign out:

const { error } = await auth.signOut()

Mandatory auth gate before user-scoped data. Before reading/writing user-owned PG rows or Storage objects, check the session and show login when absent — never "fix" data errors by silently calling signInAnonymously:

const { data } = await auth.getSession()
if (!data?.session) { navigate('/login'); return }

Completion Bar — before calling the auth task done, the generated source must have ALL of:


Extended guide

For detailed scenarios, examples, and patterns, read extended-guide.md.

Reference index

All packaged reference files (required for skill lint reachability):

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.