authentication
Overview
The Auth Api provides a complete set of authentication-related features, supporting various log-in methods, user management, and session management. The Auth Api is divided into 7 categories by purpose. Each category contains related Api methods, helping developers quickly find suitable APIs depending on specific needs.
- Authentication login: API method related to user registration and login, supporting various login methods.
- Session management: API method to manage user session status and token.
- User management: API method to get, update, and manage user information.
- Identity source management: API method to manage binding and unbinding of third-party identity sources.
- Password management: API method for password reset and modification. -Verification management: API method for Captcha sending, verify, and resend.
- Other tools: API method for other auxiliary features.
Basic Usage Examples
- Initialization Configuration
- Login status check
- User registration process
- User logout
- Password login
- Listen for authentication status
- Mobile captcha login
Publishable Key can go to Cloud Development Platform/API Key Configuration to generate
auth.detectSessionInUrl is an optional parameter for initialization. After configuration, it can automatically detect OAuth parameters (code, state) in the URL, suitable for usage scenarios such as signInWithOAuth and linkIdentity.
import cloudbase from "@cloudbase/js-sdk";
// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Optional: automatically detect OAuth parameters in the URL, suitable for signInWithOAuth, linkIdentity
},
});
const auth = app.auth;
Check login status
async function checkAuthStatus() {
const { data, error } = await auth.getSession();
if (error) {
console.error("Check login status failed:", error.message);
return false;
}
if (data.session) {
console.log("user logged in:", data.session.user);
return true;
} else {
console.log("user not logged in");
return false;
}
}
// User registration example (four-step verification process)
async function registerUser(email, password, verificationCode) {
Step 1: Send verification code
const { data, error } = await auth.signUp({
email: email,
password: password,
});
if (error) {
console.error("Send Captcha failed:", error.message);
return false;
} else {
console.log("verification code sent, Validating...");
Step 2: Verify the Captcha and complete registration.
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});
if (loginError) {
console.error("Verification failed:", loginError.message);
return false;
} else {
console.log("register successfully:", loginData.user?.email);
return true;
}
}
}
// User logout example
async function logoutUser() {
const { data, error } = await auth.signOut();
if (error) {
console.error("Logout failed:", error.message);
return false;
} else {
console.log("logout successful, session cleared");
return true;
}
}
// Password login example
async function loginWithPassword(email, password) {
const { data, error } = await auth.signInWithPassword({
email: email,
password: password,
});
if (error) {
console.error("Login failed:", error.message);
return false;
} else {
console.log("Login successful:", data.user?.email);
return true;
}
}
// Listen for authentication status adjustment
auth.onAuthStateChange((event, session, info) => {
console.log("certification status transition:", event);
switch (event) {
case "INITIAL_SESSION":
console.log("initial session established");
if (session) {
console.log("user logged in:", session.user);
} else {
console.log("user not logged in");
}
break;
case "SIGNED_IN":
console.log("user login successful:", session.user);
break;
case "SIGNED_OUT":
console.log("user logged out");
break;
case "PASSWORD_RECOVERY":
console.log("password reset");
break;
case "TOKEN_REFRESHED":
console.log("Token refreshed");
break;
case "USER_UPDATED":
console.log("user information updated");
break;
case "BIND_IDENTITY":
console.log("identity source binding result");
break;
}
});
// Complete mobile captcha login page implementation
class PhoneLoginPage {
constructor() {
this.setupEventListeners();
}
// Set up event listening
setupEventListeners() {
document.getElementById("sendCodeBtn").addEventListener("click", (e) => {
e.preventDefault();
this.sendVerificationCode();
});
document.getElementById("verifyCodeBtn").addEventListener("click", (e) => {
e.preventDefault();
this.verifyCodeAndLogin();
});
}
// Send a Captcha
async sendVerificationCode() {
const phone = document.getElementById("phone").value;
if (!phone) {
alert("Enter your phone number");
return;
}
// Verify phone number format
if (!this.validatePhone(phone)) {
alert("Enter a valid mobile number format");
return;
}
// display loading...
this.showLoading(true);
this.hideError();
try {
const { data, error } = await auth.signInWithOtp({
phone: phone,
});
if (error) {
this.handleSendCodeError(error);
} else {
this.handleSendCodeSuccess(data);
}
} catch (error) {
this.handleNetworkError(error);
} finally {
this.showLoading(false);
}
}
// Verify the Captcha and log in
async verifyCodeAndLogin() {
const code = document.getElementById("code").value;
if (!code) {
alert("Enter the Captcha");
return;
}
if (!this.verifyFunction) {
alert("Please first send verification");
return;
}
this.showLoading(true);
this.hideError();
try {
const { data, error } = await this.verifyFunction({ token: code });
if (error) {
this.handleVerifyError(error);
} else {
this.handleLoginSuccess(data);
}
} catch (error) {
this.handleNetworkError(error);
} finally {
this.showLoading(false);
}
}
// Verify phone number format
validatePhone(phone) {
const phoneRegex = /^1[3-9]\d{9}$/;
return phoneRegex.test(phone);
}
// Handle sending Captcha successfully
handleSendCodeSuccess(data) {
this.verifyFunction = data.verifyOtp;
// Display the Captcha input area
document.getElementById("verificationSection").style.display = "block";
document.getElementById("phoneSection").style.display = "none";
// Start countdown
this.startCountdown(60);
document.getElementById("success").innerText =
The Captcha has been sent to your mobile phone. Please check your inbox.
document.getElementById("success").style.display = "block";
}
// Handle sending Captcha error
handleSendCodeError(error) {
switch (error.code) {
case "invalid_phone":
document.getElementById("error").innerText =
Incorrect phone number format, please check and retry.
break;
case "user_not_found":
document.getElementById("error").innerText =
This phone number is unregistered. Please first register or use another phone number.
break;
case "resource_exhausted":
document.getElementById("error").innerText = "Frequency is too high, try again later";
break;
case "unreachable":
document.getElementById("error").innerText =
Network connection failed. Check the network settings.
break;
default:
document.getElementById("error").innerText =
"Send Captcha failed: " + error.message;
}
document.getElementById("error").style.display = "block";
}
// Handle verification error
handleVerifyError(error) {
switch (error.code) {
case "invalid_code":
document.getElementById("error").innerText = "Captcha error, please enter again";
break;
case "code_expired":
document.getElementById("error").innerText = "Captcha expired, please obtain again";
// Display the resend button
document.getElementById("resendBtn").style.display = "block";
break;
case "max_attempts_exceeded":
document.getElementById("error").innerText = "Too many verification attempts, try again later";
break;
default:
document.getElementById("error").innerText =
"Verification failed: " + error.message;
}
document.getElementById("error").style.display = "block";
}
handle successful login
handleLoginSuccess(data) {
document.getElementById("success").innerText = "Login successful. Welcome back";
document.getElementById("success").style.display = "block";
console.log("user information:", data.user);
console.log("session information:", data.session);
Navigate to the homepage after a delay
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
}
Handle network error
handleNetworkError(error) {
document.getElementById("error").innerText =
Network error, check the network and try again after.
document.getElementById("error").style.display = "block";
console.error("network error:", error);
}
// Show/Hide loading...
showLoading(show) {
document.getElementById("loading").style.display = show ? "block" : "none";
document.getElementById("sendCodeBtn").disabled = show;
document.getElementById("verifyCodeBtn").disabled = show;
}
// Hide error message
hideError() {
document.getElementById("error").style.display = "none";
}
// Start countdown
startCountdown(seconds) {
let countdown = seconds;
const btn = document.getElementById("resendBtn");
const originalText = btn.innerText;
btn.disabled = true;
const timer = setInterval(() => {
countdown--;
btn.innerText = `${countdown}s to resend`;
if (countdown <= 0) {
clearInterval(timer);
btn.disabled = false;
btn.innerText = originalText;
}
}, 1000);
}
}
// Initialize after the webpage loads
window.addEventListener("DOMContentLoaded", () => {
new PhoneLoginPage();
});
Authentication login
signUp
async signUp(params: SignUpReq): Promise<SignUpRes>
Register new user account, use intelligent signup and login process.
Phone number verification code registration is only supported in the Shanghai region
-Create a new user account -Use intelligent signup and login process: send verification code → wait for user input → intelligently determine user existence → automatically log in or register and log in. -If the user already exists, log in directly. If the user does not exist, register a new user and automatically log in.
参数
返回
示例
signInAnonymously
async signInAnonymously(params?: SignInAnonymouslyReq): Promise<SignInRes>
Anonymous login, create a temporary anonymous user account.
-Create a temporary anonymous user account -No need to provide any authentication information -Suitable for scenarios where temporary access permission is required -Before using, please confirm that anonymous login (enabled by default) is enabled in Cloud Development Platform/Identity Verification/Registration Configuration.
参数
返回
示例
signInWithPassword
async signInWithPassword(params: SignInWithPasswordReq): Promise<SignInRes>
Log in with userName, mailbox, or phone number and password.
-Support username, mailbox, or mobile number in conjunction with password as log-in methods (choose one). -Before using, please confirm that username and password login (enabled by default) is enabled in Cloud Development Platform/Identity Verification/Regular Login.
参数
返回
示例
signInWithOtp
async signInWithOtp(params: SignInWithOtpReq): Promise<SignInWithOtpRes>
Use one-time password (OTP) for login validation, supporting mailbox and SMS verification.
SMS verification code is only supported in the Shanghai region
- Send a one-time verification code via mailbox or mobile number for login validation.
- Support the full verification process: send Captcha → wait for user input → verify and log in.
- Suitable for passwordless login scenarios, offering higher security
- Before using, please confirm that log in via mailbox/SMS verification code is enabled in Cloud Development Platform/Identity Verification/Log-in Methods/Regular Login.
- If the user does not exist, a default registered user will be created. The automatic creation of the user can be controlled through the
shouldCreateUserparameter, which is set to true by default
参数
返回
示例
signInWithOAuth
async signInWithOAuth(params: SignInWithOAuthReq): Promise<SignInOAuthRes>
Generate authorization links for third-party platforms, supporting mainstream platforms such as WeChat and Google.
-Generate the authorization page URL for third-party platforms such as WeChat and Google. -Store status information in the browser session so that follow-up verification
- Support custom callback address and status parameter
- Before using, please confirm that the corresponding OAuth identity source is enabled in Cloud Development Platform/Identity Verification/Log-in Methods.
Must-Knows
- After calling this method, status information will be automatically saved to the browser session. When setting
auth.detectSessionInUrltotruein cloudbase.init, it will automatically call verifyOAuth to verify after returning from a third-party callback, otherwise you need to manually verify via the verifyOAuth method subsequently. - If no state parameter is provided, the system automatically generates a status parameter in
prd-{provider}-{random string}format -The callback URL needs to be configured in the protected domains of the Cloud Development Platform, otherwise it will return a permission error.
参数
返回
示例
signInWithIdToken
async signInWithIdToken(params: SignInWithIdTokenReq): Promise<SignInRes>
Log in with a third-party platform identity token, supporting mainstream platforms such as WeChat and Google.
-Log in with a third-party platform identity token, such as WeChat and Google. -Support specifying third-party platform identification. Third-party platforms must be configured in Cloud Development Platform/Identity Verification/Login Methods first. -Token is a required parameter
参数
返回
示例
signInWithCustomTicket
async signInWithCustomTicket(getTickFn: GetCustomSignTicketFn): Promise<SignInRes>
Use custom login invoice to log in, support complete custom login process.
-Use custom login ticket to authenticate -Support passing functions to obtain custom login invoice
- Suitable for scenarios requiring a complete custom login process
- For the detailed process of issuing a Ticket, see Custom Login
参数
Function to get custom login invoice, return Promise<string>
返回
示例
signInWithOpenId
async signInWithOpenId(params?: SignInWithOpenIdReq): Promise<SignInRes>
WeChat mini program OpenID silent login. If the user does not exist, it will determine whether to automatically register based on the login mode configuration of the corresponding identity source in the Cloud Development Platform login methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).
Only supported for use in WeChat mini program
参数
Login parameters
返回
示例
signInWithPhoneAuth
async signInWithPhoneAuth(params: SignInWithPhoneAuthReq): Promise<SignInRes>
WeChat mini program mobile phone authorization login. If the user does not exist, it will determine whether to automatically register based on the login mode configuration of the corresponding identity source in the Cloud Development Platform login methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).
Only supported for use in WeChat mini program
参数
Login parameters
返回
示例
Session Management
getSession
async getSession(): Promise<SignInRes>
Retrieve current session info and check user login status.
-Retrieve current user session information, including access token and user information. -Check whether the user is logged in. Returns an empty session if not logged in
参数
无参数
返回
示例
refreshSession
async refreshSession(refresh_token?: string): Promise<SignInRes>
Refresh the session token, extend user login status, support auto-renewal and error recovery.
-Use a refresh token to get a new access token -Extend the valid period of user sessions -Supports the use of designated refresh tokens or default tokens
参数
返回
示例
setSession
async setSession(params: SetSessionReq): Promise<SignInRes>
Use existing access token and refresh token to set user session, support external system integration and manual session management.
-Use existing access_token and refresh_token to set user session -Suitable for scenarios where tokens are obtained from an external system and sessions are set manually. -Session set successfully triggers SIGNED_IN event
参数
返回
示例
signOut
async signOut(params?: SignOutReq): Promise<SignOutRes>
User logout, clear the current session and local storage.
-Log out current user login status securely -Clear server-side session and local storage -Support redirect to specified page
- Trigger authentication status change event
参数
返回
示例
User Management
getUser
async getUser(): Promise<GetUserRes>
Obtain currently logged in user detailed information, include identity information, metadata and permission status, support user profile show and permission verification.
- Obtain currently logged in user complete information -including basic user information, metadata and identity information Users are advised to be logged in to obtain the complete information -Support checking user permissions and verification status
参数
无参数
返回
示例
refreshUser
async refreshUser(): Promise<CommonRes>
Refresh current logged-in user information.
-Refresh current logged-in user complete information
- Re-fetch the latest user data from the server
- Suitable for scenarios where user information may be updated but local cache is unsynced User must be logged in to refresh info
参数
无参数
返回
示例
updateUser
async updateUser(params: UpdateUserReq): Promise<GetUserRes>
Update current logged-in user info.
-Password update not supported. Please use resetPasswordForEmail, resetPasswordForOld, or reauthenticate to update password. -Update current logged-in user basic info and metadata -Support updating mailbox, mobile number, username, nickname, avatar, etc. -Users are advised to be logged in to update information Return upon success after update user information
参数
返回
示例
deleteUser
async deleteUser(params: DeleteMeReq): Promise<CommonRes>
Delete the current logged-in user account.
-Permanently delete the current logged-in user account. -Verify user password to confirm identity -Once deleted, all user data will be permanently removed. -Irreversible operation. Use with caution.