為使用者設定自訂的憑證附加資訊

本文將說明如何使用 Identity Platform 針對使用者設定自訂憑證附加資訊。自訂憑證附加資訊會在驗證期間插入使用者權杖。應用程式可以使用這些宣告來處理複雜的授權情境,例如根據使用者的角色限制其對資源的存取權。

設定自訂憑證

為確保安全性,請在伺服器上使用 Admin SDK 設定自訂宣稱:

  1. 如果您尚未安裝,請安裝 Admin SDK

  2. 設定要使用的自訂宣告。在以下範例中,系統會為使用者設定自訂宣稱,說明使用者是管理員:

    Node.js

    // Set admin privilege on the user corresponding to uid.
    
    getAuth()
      .setCustomUserClaims(uid, { admin: true })
      .then(() => {
        // The new custom claims will propagate to the user's ID token the
        // next time a new one is issued.
      });

    Java

    // Set admin privilege on the user corresponding to uid.
    Map<String, Object> claims = new HashMap<>();
    claims.put("admin", true);
    FirebaseAuth.getInstance().setCustomUserClaims(uid, claims);
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.

    Python

    # Set admin privilege on the user corresponding to uid.
    auth.set_custom_user_claims(uid, {'admin': True})
    # The new custom claims will propagate to the user's ID token the
    # next time a new one is issued.

    Go

    // Get an auth client from the firebase.App
    client, err := app.Auth(ctx)
    if err != nil {
    	log.Fatalf("error getting Auth client: %v\n", err)
    }
    
    // Set admin privilege on the user corresponding to uid.
    claims := map[string]interface{}{"admin": true}
    err = client.SetCustomUserClaims(ctx, uid, claims)
    if err != nil {
    	log.Fatalf("error setting custom claims %v\n", err)
    }
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.

    C#

    // Set admin privileges on the user corresponding to uid.
    var claims = new Dictionary<string, object>()
    {
        { "admin", true },
    };
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims);
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.
  3. 在下次將自訂權利要求傳送至伺服器時,驗證權利要求:

    Node.js

    // Verify the ID token first.
    getAuth()
      .verifyIdToken(idToken)
      .then((claims) => {
        if (claims.admin === true) {
          // Allow access to requested admin resource.
        }
      });

    Java

    // Verify the ID token first.
    FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdToken(idToken);
    if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) {
      // Allow access to requested admin resource.
    }

    Python

    # Verify the ID token first.
    claims = auth.verify_id_token(id_token)
    if claims['admin'] is True:
        # Allow access to requested admin resource.
        pass

    Go

    // Verify the ID token first.
    token, err := client.VerifyIDToken(ctx, idToken)
    if err != nil {
    	log.Fatal(err)
    }
    
    claims := token.Claims
    if admin, ok := claims["admin"]; ok {
    	if admin.(bool) {
    		//Allow access to requested admin resource.
    	}
    }

    C#

    // Verify the ID token first.
    FirebaseToken decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);
    object isAdmin;
    if (decoded.Claims.TryGetValue("admin", out isAdmin))
    {
        if ((bool)isAdmin)
        {
            // Allow access to requested admin resource.
        }
    }
    
  4. 如要判斷使用者有哪些自訂憑證附加資訊,請按照下列步驟操作:

    Node.js

    // Lookup the user associated with the specified uid.
    getAuth()
      .getUser(uid)
      .then((userRecord) => {
        // The claims can be accessed on the user record.
        console.log(userRecord.customClaims['admin']);
      });

    Java

    // Lookup the user associated with the specified uid.
    UserRecord user = FirebaseAuth.getInstance().getUser(uid);
    System.out.println(user.getCustomClaims().get("admin"));

    Python

    # Lookup the user associated with the specified uid.
    user = auth.get_user(uid)
    # The claims can be accessed on the user record.
    print(user.custom_claims.get('admin'))

    Go

    // Lookup the user associated with the specified uid.
    user, err := client.GetUser(ctx, uid)
    if err != nil {
    	log.Fatal(err)
    }
    // The claims can be accessed on the user record.
    if admin, ok := user.CustomClaims["admin"]; ok {
    	if admin.(bool) {
    		log.Println(admin)
    	}
    }

    C#

    // Lookup the user associated with the specified uid.
    UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid);
    Console.WriteLine(user.CustomClaims["admin"]);

設定自訂宣告時,請注意下列事項:

  • 自訂聲明的大小不得超過 1000 個位元組。如果嘗試傳遞的聲明大於 1000 個位元組,系統會傳回錯誤。
  • 權杖核發時,系統會將自訂權杖附加資訊插入使用者 JWT。權杖重新整理後,才能使用新的宣告。您可以呼叫 user.getIdToken(true) 來靜默重新整理權杖。
  • 為維持連續性和安全性,請只在安全的伺服器環境中設定自訂宣告。

後續步驟