Skip to main content

User-Based Security Control

Storage security rules combined with user authentication can achieve identity verification, and developers can perform granular resource access control based on user identity information.

User Identity Authentication

When an authenticated user makes a request, the system populates the auth variable with the user's unique id uid and login method loginType. When an unauthenticated user makes a request, the auth variable is null.

Through the auth variable, file access can be controlled based on identity using the following common methods:

  • Public: The auth value is not evaluated.
  • Accessible only to logged-in users: Check that auth is not null.
  • User-private: Check if auth.uid equals the resource's openid.
  • For a specific login method: Restrict access to anonymously logged-in users by checking that auth.loginType is not ANONYMOUS

Public

Any rule that does not consider auth can be regarded as a public rule, as it disregards the user's authentication context. These rules are well-suited for scenarios involving the presentation of public data (static resource content).

{
"read": "resource.openid != null"
}

Accessible to logged-in users

In some cases, you may want to restrict access to user data to only logged-in users. For example, only logged-in users can view discussions in the forum. Since the auth variable is null for all unauthenticated users, you can set the following rules:

{
"read": "auth != null"
}

User-private

The most common use scenario for auth` is to provide fine-grained access control for personal user resources, such as uploading private photos. Cloud storage files contain file owner information (user unique id), which can be restricted in rules as follows:

{
"read": "auth.uid == resource.openid",
"write": "auth.uid == resource.openid"
}

Peer Authentication: Restrict Access to Anonymously Logged-in Users

In applications, you may want to display different content for users with different login methods. In this case, you can verify auth.loginType, whose value is one of the following enumerated values:

Enum ValueLogin Method Description
WECHAT_PUBLICWeChat Official Account
WECHAT_OPENWeChat Open Platform
ANONYMOUSAnonymous login
EMAILEmail Login
CUSTOMCustom Login

If you wish to display limited content to anonymously logged-in users, you can restrict it with the following rules:

{
"read": "auth.loginType !== 'ANONYMOUS'"
}

Complete Sample

In summary, for a photo album application, the goal is to allow all logged-in users to upload and browse gallery photos, while denying access to unauthenticated users. However, anonymous login is permitted, granting browse-only access without upload capabilities. Thus, the following rules can be configured for storage.

{
"read": "auth != null",
"write": "auth.loginType != 'ANONYMOUS' && auth.openid == resource.openid"
}