Skip to main content

Login Methods Practical Tutorial

CloudBase provides cross-platform login authentication capabilities, enabling you to build a user system, including anonymous login, email login, WeChat authorized login, custom login, username and password login, and mobile SMS verification code login.

Prerequisites

Activate environment and select Pay-As-You-Go as the billing mode.

Login Authentication Methods

CloudBase provides the following login authentication methods for different user scenarios:

Login TypeScenario
UnauthenticatedAfter allowing unauthenticated access, users can access the application without logging in.
Anonymous LoginUsers log in to CloudBase with a temporary anonymous identity without registration.
Email LoginUsers log in with their own email+password.
WeChat Authorization Login
  • WeChat Official Accounts Platform-authorized official account web pages.
  • WeChat Open Platform-authorized websites (requires certification).
Custom LoginDevelopers can fully take over the login process, such as integrating with their own account systems or customizing login logic.
Username and Password LoginUsers log in with their own username and password.
SMS Verification Code LoginUsers log in with their own phone number and verification code.

Login Types

Unauthenticated

  1. Log in to the CloudBase console, and under Login Authorization, turn on the Unauthenticated Access option.
  2. Go to the Environment > Security Configuration page and click Add Domain.
  3. Configure custom security rules to allow unauthenticated access.
  4. Initialize the SDK to initiate a call. For more details, see Usage Process.

Anonymous Login

  1. Log in to the CloudBase console, and on the Login Authorization page, turn on the Anonymous Login option to enable anonymous login.

  1. Go to the Environment > Security Configuration page and click Add Domain.

  1. Login Process Development.
import cloudbase from '@cloudbase/js-sdk';

const app = cloudbase.init({
env: 'xxxx-yyy'; // Environment ID
});

const auth = app.auth();

async function login(){
await auth.anonymousAuthProvider().signIn();
// When anonymous login is successful, the isAnonymous field in the login status is true
const loginState = await auth.getLoginState();
console.log(loginState.isAnonymousAuth); // true
}

login();
The effect of anonymous login is as shown in the figure below:

Email Login

  1. Go to the CloudBase Console, and on the Login Authorization settings page, enable email login.

  1. Click Configure Sender, and fill in your email SMTP account information.
  1. Click Application Configuration to configure your application name and auto-redirect link.
  1. After successful configuration, a test email will be received in your email.

  1. Sample code is as follows:
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
});

WeChat Official Account Login

Prerequisites

  • On the Register Official Account page, successfully register a Service Account ("Subscription Accounts" do not have permissions for the "webpage authorization interface").
  • Log in to the newly registered Service Account, go to Settings > Basic Information > WeChat Verification section, and complete WeChat verification.
  • Complete adding the webpage authorization domain for the Official Account.
  • Go to the Development > Basic Configuration page to obtain the AppId and AppSecret of the Service Account.

Operation Steps

  1. Log in to the CloudBase Console, and in Login Authorization, click to enable WeChat Official Account login authorization.
  2. Click the Enable button, then enter the corresponding AppId and AppSecret.
  3. Go to the Environment > Security Configuration page and click Add Security Domain.
  4. Sample code is as follows:
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
});

WeChat Open Platform Login

Prerequisites

  • Complete the registration on WeChat Open Platform.
  • Log in to the newly registered WeChat Open Platform, go to Account Center > Developer Qualification Certification page to complete the application for WeChat Verification.
  • Successfully create a web application on the WeChat Open Platform.
  • Obtain the AppId and AppSecret of the web application on the WeChat Open Platform.

Operation Steps

  1. Log in to the CloudBase Console, and in Login Authorization, click to enable WeChat Open Platform login authorization.
  2. Click the Enable button, then enter the corresponding AppId and AppSecret.
  3. Add the CloudBase SDK to your Web application.
<script src="//static.cloudbase.net/cloudbase-js-sdk/1.6.0/cloudbase.full.js"></script>

<script>
const app = cloudbase.init({
// Your Environment id
env: "your-env-id",
});
</script>
Note

Copy the following code snippet and paste it at the bottom of your HTML code, before other script tags.

const auth = app.auth();
const provider = auth.weixinAuthProvider({ appid: "...", scope: "xxxx" });
async function login() {
// 1. It is recommended to check whether you are already logged in before logging in.
const loginState = await auth.getLoginState();
if (!loginState) {
// 2. Call the WeChat login API
provider.getRedirectResult().then((loginState) => {
if (loginState) {
// Login successful. Local login status exists.
} else {
// Not logged in, trigger WeChat login
provider.signInWithRedirect();
}
});
}
}
login();

Custom Login

Custom login applies to scenarios where developers need to control the authentication process themselves and maintain their own account systems.

  1. Log in to the CloudBase console. On the Login Authorization page, in the Custom login section, click Private Key Download to obtain the custom login private key.
Note

The private key is a file containing JSON data. Please save the downloaded or copied private key file to your server or cloud function, assuming the path is /path/to/your/tcb_custom_login.json.

  • The private key file is an important credential for verifying administrator identity. Be sure to keep it safe and avoid leakage.
  • Each time a private key file is generated, it invalidates the previously generated private key file after 2 hours.
  1. Call the CloudBase server-side SDK. Pass the custom login private key during initialization, then issue a Ticket and return it to the client side.
const cloudbase = require("@cloudbase/node-sdk");
// 1. Initialize SDK.
const app = cloudbase.init({
env: "your-env-id",
// Pass the custom login private key credentials:
require("/path/to/your/tcb_custom_login.json")
});
// 2. Developer-defined unique user identifier.
const customUserId = "your-customUserId";
// 3. Create a ticket.
const ticket = app.auth().createTicket(customUserId);
// 4. Return the ticket to the client. return ticket;
Note

Developers can also write a cloud function to generate Tickets and set up an HTTP access service for it. The client side can then obtain Tickets through HTTP requests. For detailed implementation, refer to Accessing Cloud Functions via HTTP.

  1. After the client application obtains the Ticket, it can use the Ticket to log in to CloudBase by calling the auth.signInWithTicket() method provided by the client SDK.
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({ env: "your-env-id" });
const auth = app.auth();
async function login() {
// 1. It is recommended to check whether you are already logged in before logging in.
const loginState = await auth.getLoginState();
if (!loginState) {
// 2. Request the developer's service API to obtain the ticket.
const ticket = await fetch("...");
// 3. Log in to CloudBase.
await auth.customAuthProvider().signIn(ticket);
}
}
login();

The overall process is as follows:

Username-Password Login

  1. Log in to the CloudBase console, and in Login Authorization, click to enable Username-Password Login.
  2. Initialize the SDK.
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
});
  1. Log in using other methods.
Note

Before binding a username, users must first log in using other methods, such as email login or WeChat Official Account login, but excluding anonymous login.

The following uses Email Login as an example:

const auth = app.auth();
await auth.signInWithEmailAndPassword(email, password); // Email login
  1. Bind the username.
const auth = app.auth();
if (!(await auth.isUsernameRegistered(username))) {
// Check whether the username has been bound.
await auth.currentUser.updateUsername(username); // Bind username
}
  1. Sample code is as follows:
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
});

SMS Verification Code Login

  1. Log in to the CloudBase console, and in Login Authorization, click to enable SMS verification code login.
  2. Click Signature Configuration under the operation bar, enter the corresponding parameters, and then click Save.
  1. Initialize the SDK.
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
});
  1. Register an account using a phone number: first, the user needs to enter their phone number, then call the SDK's send SMS verification code interface.
// Send the verification code
app
.auth()
.sendPhoneCode("Phone number")
.then((res) => {
console.log("Verification code sent successfully");
});

// Verification code + password registration
app
.auth()
.signUpWithPhoneCode("Phone number", "six-digit verification code", "custom password")
.then((res) => {
console.log("Registration successful");
});
  1. The phone password and SMS verification code login methods are as follows:
app
.auth()
.signInWithPhoneCodeOrPassword({
phoneNumber: "Phone Number",
phoneCode: "Verification Code",
})
.then((res) => {
// Login successful
});