Skip to main content

Best Practices

This document provides best practice guidelines for CloudBase authentication and permission control, helping developers quickly understand and integrate the authentication module to build secure and reliable application systems.

Feature Introduction

Core Concepts

The CloudBase authentication system consists of two core components:

  • Authentication: Solves the "who is the user" problem, supporting multiple login methods such as phone number, email, WeChat, anonymous, etc.
  • Permission Control: Solves the "what resources can the user access" problem, managing resource access permissions through roles and policies in a fine-grained manner.

Complete authentication integration requires understanding: Login Methods → Role System → Member Management → Permission Policies → Security Configuration.

Login Methods

CloudBase supports multiple login methods. You need to enable them first in CloudBase Console/Authentication/Login Methods. You can flexibly choose according to application scenarios:

Login MethodApplicable ScenariosConfiguration Entry
Phone Number LoginApplications requiring real-nameLogin Method Management
Email LoginEnterprise apps, international appsLogin Method Management
WeChat LoginWeChat ecosystem applicationsLogin Method Management
Anonymous LoginFeatures that don't require registrationRegistration Configuration
Username & PasswordTraditional web applicationsLogin Method Management

💡 Suggestion: Applications can enable multiple login methods simultaneously, allowing users to choose independently.

Role System

Role Definition

Roles are the carrier of permissions. By assigning users to different roles, fine-grained permission management is achieved. The system provides the following preset roles:

Role TypeDescriptionTypical Use Cases
AdministratorHas all permissions, can manage environments, members, resourcesProject leader, technical supervisor
All UsersIncludes all logged-in and non-logged-in usersPublic content access control
Organization MembersUsers added to the organization structureEnterprise internal application access
External UsersNon-anonymous logged-in users except organization membersC-end application users requiring login, such as e-commerce apps
Anonymous UsersVisitors who are not logged inPublic pages, marketing landing pages

⚠️ Important Note: The administrator role has the highest privileges in the system, including deleting data, modifying configurations, managing members, and other sensitive operations. Please use with caution.

Custom Roles

When preset roles cannot meet business needs, you can create custom roles:

  1. Visit the CloudBase Console/Authentication/Permission Control page
  2. Click "Create Role"
  3. Set role identifier and description, for example:
    • content_editor: Content Editor
    • data_analyst: Data Analyst
    • finance_admin: Finance Administrator
  4. Configure access permissions for the role

Role Permission Merging Rules

When a user has multiple roles, permission merging follows these rules:

  • Allow permissions are unioned: Users have the sum of all allowed permissions from all roles
  • Deny permissions take precedence: A deny rule from any role overrides allow rules from other roles

Example:

User roles: Content Editor + Data Analyst
- Content Editor: Allow access to article table (read, write, update)
- Data Analyst: Allow access to order table (read only)
- Result: User can read and write articles, can view orders

Member Management

Adding Members

There are two ways to add users to roles:

Method 1: Add members in roles

  1. Visit the CloudBase Console/Authentication/Permission Control page and find the target role
  2. Click "Configure Members" for the role
  3. Click "Add Members" to batch select users
  4. Takes effect immediately after confirmation

Method 2: Manage in organization structure

  1. Visit the CloudBase Console/Authentication/Organization Structure page
  2. Create department and position structures
  3. Add users to corresponding organization nodes
  4. Batch associate roles to users

Member Permission Changes

There are two ways to modify user permissions:

  • Modify role permissions: All users under that role automatically inherit new permissions
  • Adjust user roles: Remove users from a role or add them to a new role

💡 Tip: Permission changes may take some time to take effect. It is recommended that users log out and log in again.

Permission Control

Permission Configuration Model

CloudBase's permission control is based on the following model:

Permission Configuration = Resource Scope + Data Scope + Operation Type
  • Resource Scope: Which resources can the role access (data tables, cloud functions, cloud storage, etc.)
  • Data Scope: Which data can be accessed (all data, only data created by oneself, data meeting specific conditions)
  • Operation Type: What operations can be performed (view, create, update, delete)

Data Row Permissions

Control which data rows (records) users can access through row-level permissions. Common configuration methods:

  • All data: Users can access all data
  • Only own data: Users can only access data they created
  • Data meeting specific conditions: Users can only access data meeting specific conditions (such as belonging to a department, specific status, etc.)

Example: Sales personnel can only view customer data they are responsible for

Data Column Permissions

Control which fields (columns) users can access through field-level permissions. You can configure:

  • Readable fields: List of fields users can view
  • Hidden fields: Sensitive fields that are invisible to users

Example: Hide cost and profit fields from sales personnel

💡 Tip: Row-level permissions and field-level permissions can be used simultaneously to achieve more fine-grained data access control.

Operation Permissions

Configure operation permissions for roles on resources:

  • View (Read): Read data
  • Create (Create): Add new data
  • Update (Update): Edit data
  • Delete (Delete): Delete data

Different resource types may support different operation permissions. Please refer to the corresponding resource documentation:

Typical Scenario Practice Examples

Scenario 1: Personal Blog Website

Requirements Description

A personal blog needs to support three scenarios: visitor browsing, user commenting, and blogger management.

Role Planning

RolePermission ScopeTarget Users
Anonymous UserBrowse articles, view commentsAll visitors
Registered UserBrowse articles, post comments, likeRegistered readers
AdministratorPublish articles, manage comments, site settingsBlog owner

Data Permission Configuration

Article table (blog_articles) permission settings:

  • Anonymous users: Can only read published articles
  • Registered users: Can read published articles and their own drafts
  • Administrator: Has all permissions

Comment table (comments) permission settings:

  • Anonymous users: Can only view comments
  • Registered users: Can view all comments, can update/delete their own comments
  • Administrator: Has all permissions

Implementation Steps

  1. Enable anonymous login: Enable "Allow anonymous login" in Login Method Management
  2. Configure database permissions: Configure access permissions for corresponding roles in the database collection's permission settings. Please refer to: Document Database Permissions
  3. Frontend calls anonymous login by default:
import cloudbase from '@cloudbase/js-sdk';

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

const auth = app.auth();

// Execute anonymous login by default
auth.signInAnonymously();

Scenario 2: Enterprise Internal Management System

Requirements Description

Enterprise management systems need to distinguish access permissions for different departments and positions to achieve data isolation.

Role Planning

Custom role creation:

  1. Create custom roles on the Permission Control page
  2. Set role identifiers according to job responsibilities, for example:
    • content_editor: Content Editor
    • data_analyst: Data Analyst
    • finance_admin: Finance Administrator

Data Permission Configuration

Row-level permission configuration:

Implement "users can only access data from their own department":

数据行权限配置

Field-level permission configuration:

Hide sensitive fields (such as cost, profit):

数据列权限配置

Scenario 3: Collaborative Editing Platform

Requirements Description

A multi-user collaborative document editing platform that allows users to edit documents created by others, but requires strict permission control.

Role Planning

RolePermission ScopeTarget Users
Regular UserView all documents, edit own documentsRegistered users
CollaboratorView all documents, edit authorized documentsInvited users
AdministratorFull permissions for all documents (view, edit, delete)Team managers

Implementation Solutions

⚠️ Security Warning: Allowing modification of others' data is a high-risk operation and must be implemented with careful permission control.

Solution 1: Modify data through cloud functions (Recommended)

Cloud functions execute on the server side and can bypass client-side permission restrictions, but strict permission verification must be implemented inside the function:

// Cloud Function: editDocument
const cloudbase = require('@cloudbase/node-sdk');
const app = cloudbase.init();
const db = app.database();

exports.main = async (event, context) => {
const { documentId, newContent } = event;
const { userInfo } = context;

// 1. Verify user login status
if (!userInfo || !userInfo.uid) {
return { code: 401, message: 'Not logged in' };
}

// 2. Query document information
const doc = await db.collection('documents')
.doc(documentId)
.get();

if (!doc.data || doc.data.length === 0) {
return { code: 404, message: 'Document not found' };
}

const document = doc.data[0];

// 3. Permission verification: Check if user is author or collaborator
const isOwner = document._openid === userInfo.openid;
const isCollaborator = document.collaborators &&
document.collaborators.includes(userInfo.uid);

if (!isOwner && !isCollaborator) {
return { code: 403, message: 'No permission to edit this document' };
}

// 4. Execute update
const result = await db.collection('documents')
.doc(documentId)
.update({
content: newContent,
lastEditBy: userInfo.uid,
lastEditAt: new Date()
});

return { code: 0, message: 'Update successful', data: result };
};

Solution 2: Configure through security rules (Fine-grained control)

For scenarios requiring more complex and fine-grained permission control, you can use CloudBase's security rules feature.

Resources supporting security rules in CloudBase:

Resource TypeSecurity Rules DocumentationApplicable Scenarios
Document DatabaseDatabase Security RulesDocument-level, field-level fine-grained permission control
Cloud StorageCloud Storage Security RulesFile upload, download, delete permission control
Cloud FunctionsCloud Function Security RulesFunction invocation permission control (client SDK only)

Implementing collaborative editing using security rules:

// Document database security rules example
{
// Read permission: All logged-in users can view documents
"read": "auth != null",

// Write permission: Author, collaborators, or administrators can edit
"write": "doc._openid == auth.openid || doc.collaborators.includes(auth.uid) || auth.role == 'admin'"
}

Security Configuration Recommendations

Cautious Use of Administrator Role

⚠️ Important Note: The administrator role has the highest privileges in the system, including deleting data, modifying configurations, managing members, and other sensitive operations.

Recommended practices:

  • Create custom roles with restricted permissions for daily operations
  • Only use administrator accounts when necessary
  • Regularly review the list of administrator accounts
  • Enable two-factor authentication for administrator accounts

Principle of Least Privilege

Follow the "principle of least privilege", granting users only the minimum permissions needed to complete their work:

✓ Recommended: Sales personnel can only view customer data they are responsible for
✗ Avoid: Sales personnel can view all customer data

Frequently Asked Questions and Solutions

Q1: Why can't users access resources even after permissions have been added?

Troubleshooting steps:

  1. Check role assignment: Confirm that the user has been assigned to the correct role
  2. Check policy status: Confirm that the policy has been saved and associated with the correct role
  3. Check effective time: Permission changes may take some time to take effect. It is recommended that users log out and log in again
  4. Check gateway policy: May be blocked by gateway-level restrictions. Check the gateway permission policy associated with the user
  5. View error messages: View the specific denial reason and solve it accordingly

Q2: How are permissions from multiple roles merged?

When a user has multiple roles, permission merging follows these rules:

  • Allow permissions are unioned: Users have the sum of all allowed permissions from all roles
  • Deny permissions take precedence: A deny rule from any role overrides allow rules from other roles

Example:

User roles: Content Editor + Data Analyst
- Content Editor: Allow access to article table (read, write, update)
- Data Analyst: Allow access to order table (read only)
- Result: User can read and write articles, can view orders