0Pricing
Firebase Auth & Realtime Database Apps · Lektion

Benutzerdefinierte Claims und Sicherheitsregeln

Definieren Sie benutzerdefinierte Claims für Benutzer und verknüpfen Sie sie mit Firebase Security Rules, um den Zugriff auf Ressourcen zu steuern

Benutzerdefinierte Claims und Sicherheitsregeln ist eine kostenlose Firebase Auth & Realtime Database Apps-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Firebase Auth & Realtime Database Apps-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Firebase Auth & Realtime Database Apps-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.

Häufig gestellte Fragen

Ist die Lektion „Benutzerdefinierte Claims und Sicherheitsregeln“ kostenlos?

Ja — der vollständige Text von „Benutzerdefinierte Claims und Sicherheitsregeln“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Firebase Auth & Realtime Database Apps-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Firebase Auth & Realtime Database Apps-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Benutzerdefinierte Claims und Sicherheitsregeln“?

Definieren Sie benutzerdefinierte Claims für Benutzer und verknüpfen Sie sie mit Firebase Security Rules, um den Zugriff auf Ressourcen zu steuern Du übst Firebase Auth & Realtime Database Apps mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Firebase Auth & Realtime Database Apps zu starten?

Keine Vorkenntnisse erforderlich. Firebase Auth & Realtime Database Apps auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.

Wie lange dauert die Lektion „Benutzerdefinierte Claims und Sicherheitsregeln“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Firebase Auth & Realtime Database Apps-Lektion Code schreiben und ausführen?

Ja. Jede Firebase Auth & Realtime Database Apps-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Authentifizierung per Telefonnummer
  2. Multi-Faktor-Authentifizierung (MFA)
  3. Benutzerdefinierte Claims und Sicherheitsregeln
  4. Kontoverknüpfung und Providerverwaltung
← Zurück zu Firebase Auth & Realtime Database Apps