0Pricing
Firebase Auth & Realtime Database Apps · レッスン

カスタムクレームとセキュリティルール

ユーザー向けのカスタムクレームを定義し、Firebase Security Rulesと連携させてリソースへのアクセスを制御します。

「カスタムクレームとセキュリティルール」はCoddyKit上の無料Firebase Auth & Realtime Database Appsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.

よくある質問

「カスタムクレームとセキュリティルール」レッスンは無料ですか?

はい。「カスタムクレームとセキュリティルール」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Firebase Auth & Realtime Database Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Firebase Auth & Realtime Database Appsコースには全4レッスンが含まれています。

「カスタムクレームとセキュリティルール」で何を学びますか?

ユーザー向けのカスタムクレームを定義し、Firebase Security Rulesと連携させてリソースへのアクセスを制御します。 ブラウザで直接実行するハンズオンコードでFirebase Auth & Realtime Database Appsを演習し、24時間対応の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に戻る