0Pricing
Firebase Auth & Realtime Database Apps · 课时

自定义声明与安全规则

为用户定义自定义声明,并将其与 Firebase 安全规则集成,以控制对资源的访问

自定义声明与安全规则 是 CoddyKit 上的免费 Firebase Auth & Realtime Database Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Firebase Auth & Realtime Database Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Custom Claims

Beyond basic user authentication, Firebase allows you to define Custom Claims. These are key-value pairs that you can add to a user's ID token, providing extra information about the user.

Think of them as custom labels or badges attached to a user's identity.

Why Use Custom Claims?

Custom claims are powerful for implementing role-based access control (RBAC) or granting specific permissions within your app. Instead of just knowing 'who' the user is, you can know 'what' they are allowed to do.

  • Designate users as 'admin', 'editor', or 'subscriber'.
  • Grant access to premium features or content.
  • Control data access based on custom attributes.

Setting Claims (Server-Side)

Custom claims are sensitive and must be set by a trusted environment, like your backend server, using the Firebase Admin SDK. This prevents malicious users from giving themselves elevated privileges.

When claims are set, the user's ID token is updated. Clients need to refresh their token to receive the new claims.

Simulating Claim Setting

This conceptual example shows how claims work. On a real backend, the Admin SDK would update a user's profile, and these claims would then be available in their ID token.

import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    String userId = "user123";
    Map<String, Object> claims = new HashMap<>();

    // --- Server-side action (simulated) ---
    System.out.println("Server sets claims for " + userId);
    claims.put("role", "admin");
    claims.put("level", "premium");

    // --- Client-side action (simulated after token refresh) ---
    System.out.println("\nClient receives ID token with claims:");
    System.out.println("User ID: " + userId);
    System.out.println("Claims: " + claims);

    // Client checks for specific claim
    if (claims.containsKey("role") && claims.get("role").equals("admin")) {
      System.out.println("Access check: User is an admin.");
    } else {
      System.out.println("Access check: Not an admin.");
    }
  }
}

Accessing Claims (Client-Side)

Once a user is logged in and their ID token is refreshed (e.g., after login or explicitly refreshing), your client-side application can read these custom claims from the token.

The claims are embedded within the ID token, which is a JWT (JSON Web Token).

How Claims Power Rules

The true power of custom claims comes when you combine them with Firebase Security Rules. Any custom claim you set on a user's ID token is automatically available within your security rules.

This allows you to create highly specific and dynamic access control logic for your Realtime Database or Cloud Firestore.

Rule Example: Admin Access

Here's how a Firebase Realtime Database Security Rule might use a custom admin: true claim to restrict access to a specific data path.

Only users with this claim in their token would be able to read or write to /adminContent.

{
  "rules": {
    "adminContent": {
      // Only users with 'admin: true' claim can read/write
      ".read": "auth.token.admin === true",
      ".write": "auth.token.admin === true"
    },
    "publicContent": {
      // Anyone authenticated can read, no special claims needed
      ".read": "auth != null",
      ".write": "false"
    }
  }
}

Rule Example: Premium Content

You can also use claims for different levels of access. This rule grants read access to /premiumContent only if the user has a level: 'premium' claim.

This is much more flexible than just checking if a user is logged in.

{
  "rules": {
    "premiumContent": {
      // Only users with 'level: premium' claim can read
      ".read": "auth.token.level === 'premium'",
      ".write": "false"
    },
    "users": {
      "$uid": {
        ".read": "auth.uid === $uid",
        ".write": "auth.uid === $uid"
      }
    }
  }
}

Best Practices for Claims

To ensure efficient and secure use of custom claims:

  • Keep claims small: ID tokens have size limits.
  • Don't store sensitive data: Claims are base64 encoded, not encrypted.
  • Use for authorization: Not for general data storage.
  • Token refresh: Remind users to refresh their ID token if claims change.

Claims Quiz

You've learned how custom claims enhance user roles and security rules. Which statement accurately describes a key aspect of Firebase Custom Claims?

Recap: Custom Claims & Rules

This lesson covered Firebase Custom Claims, a powerful feature for advanced user management.

  • Custom claims allow you to add custom attributes to user ID tokens.
  • They are set securely using the Firebase Admin SDK on your backend.
  • These claims are seamlessly integrated with Firebase Security Rules, enabling robust, role-based access control for your app's resources.
  • Always remember to refresh the client's ID token for changes to take effect.

常见问题解答

「自定义声明与安全规则」课时是免费的吗?

是的 — 「自定义声明与安全规则」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Firebase Auth & Realtime Database Apps 课程的其余内容,请升级到 CoddyKit PRO。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。

「自定义声明与安全规则」这节课中我会学到什么?

为用户定义自定义声明,并将其与 Firebase 安全规则集成,以控制对资源的访问 你通过在浏览器中直接运行的动手代码来练习 Firebase Auth & Realtime Database Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Firebase Auth & Realtime Database Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Firebase Auth & Realtime Database Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「自定义声明与安全规则」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Firebase Auth & Realtime Database Apps 课中编写并运行代码吗?

能。每节 Firebase Auth & Realtime Database Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 电话号码身份验证
  2. 多重身份验证(MFA)
  3. 自定义声明与安全规则
  4. 账户关联与身份验证提供商管理
← 返回 Firebase Auth & Realtime Database Apps