कस्टम दावों और सुरक्षा नियमों की मदद से ऐक्सेस कंट्रोल करना

Firebase एडमिन SDK टूल की मदद से, उपयोगकर्ता खातों पर कस्टम एट्रिब्यूट तय किए जा सकते हैं. इससे कई तरह की ऐक्सेस कंट्रोल रणनीतियां लागू की जा सकती हैं. इनमें Firebase ऐप्लिकेशन में भूमिका के आधार पर ऐक्सेस कंट्रोल शामिल है. ये कस्टम एट्रिब्यूट, उपयोगकर्ताओं को अलग-अलग लेवल का ऐक्सेस (भूमिकाएं) दे सकते हैं, जो ऐप्लिकेशन के सुरक्षा नियमों से लागू होते हैं.

इन सामान्य मामलों में, उपयोगकर्ता की भूमिकाओं को तय किया जा सकता है:

  • डेटा और संसाधन ऐक्सेस करने के लिए, किसी उपयोगकर्ता को एडमिन के अधिकार देना.
  • उपयोगकर्ता से जुड़े अलग-अलग ग्रुप के बारे में जानकारी देना.
  • कई लेवल वाला ऐक्सेस देना:
    • पैसे चुकाकर सदस्यता लेने वाले/बिना पेमेंट वाले सदस्यों में फ़र्क़ करना.
    • मॉडरेटर और सामान्य उपयोगकर्ताओं के बीच अंतर करना.
    • शिक्षक/छात्र/छात्रा के लिए आवेदन वगैरह
  • उपयोगकर्ता पर कोई अतिरिक्त आइडेंटिफ़ायर जोड़ें. उदाहरण के लिए, कोई Firebase उपयोगकर्ता किसी दूसरे सिस्टम में एक अलग यूआईडी पर मैप कर सकता है.

आइए, एक ऐसे मामले पर विचार करते हैं जिसमें आपको डेटाबेस नोड "adminContent" के ऐक्सेस को सीमित करना है. ऐसा करने के लिए, एडमिन उपयोगकर्ताओं की सूची में मौजूद डेटाबेस को लुकअप करें. हालांकि, नीचे दिए गए रीयल टाइम डेटाबेस नियम के साथ, admin नाम के कस्टम उपयोगकर्ता दावे का इस्तेमाल करके, इस मकसद को ज़्यादा बेहतर तरीके से हासिल किया जा सकता है:

{
  "rules": {
    "adminContent": {
      ".read": "auth.token.admin === true",
      ".write": "auth.token.admin === true",
    }
  }
}

कस्टम उपयोगकर्ता दावे, उपयोगकर्ता के पुष्टि करने वाले टोकन के ज़रिए ऐक्सेस किए जा सकते हैं. ऊपर दिए गए उदाहरण में, सिर्फ़ उन उपयोगकर्ताओं के पास adminContent नोड को पढ़ने/लिखने का ऐक्सेस होगा जिनके लिए admin 'सही है' पर सेट है. आईडी टोकन में पहले से ही ये बातें शामिल होती हैं. इसलिए, एडमिन की अनुमतियों की जांच करने के लिए, अलग से प्रोसेसिंग या लुकअप की ज़रूरत नहीं होती. इसके अलावा, आईडी टोकन, इन कस्टम दावों को डिलीवर करने का एक भरोसेमंद तरीका है. पुष्टि किए गए सभी ऐक्सेस के लिए ज़रूरी है कि उनसे जुड़े अनुरोध को प्रोसेस करने से पहले, आईडी टोकन की पुष्टि की जाए.

इस पेज पर दिए गए कोड के उदाहरण और समाधान, क्लाइंट-साइड Firebase Auth API और Admin SDK से मिले सर्वर-साइड Auth API, दोनों से लिए जाते हैं.

एडमिन SDK से, पसंद के मुताबिक उपयोगकर्ता के दावों को सेट करने और उनकी पुष्टि करने की सुविधा

पसंद के मुताबिक किए गए दावों में संवेदनशील डेटा हो सकता है. इसलिए, इन्हें सिर्फ़ Firebase एडमिन SDK टूल से मिले खास अधिकार वाले सर्वर एनवायरमेंट से ही सेट किया जाना चाहिए.

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.

शुरू करें

// 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.

कस्टम दावों के ऑब्जेक्ट में, OIDC वाली रिज़र्व की गई कुंजी का नाम या Firebase का रिज़र्व किया गया नाम नहीं होना चाहिए. कस्टम दावों का पेलोड 1000 बाइट से ज़्यादा नहीं होना चाहिए.

बैकएंड सर्वर को भेजा गया आईडी टोकन, उपयोगकर्ता की पहचान और ऐक्सेस लेवल की पुष्टि करने के लिए, एडमिन SDK टूल का इस्तेमाल इस तरह कर सकता है:

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

शुरू करें

// 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.
    }
}

आपके पास किसी उपयोगकर्ता के मौजूदा कस्टम दावों को भी देखने का विकल्प होता है. ये दावे, उपयोगकर्ता ऑब्जेक्ट पर प्रॉपर्टी के तौर पर उपलब्ध होते हैं:

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'))

शुरू करें

// 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"]);

आप customClaims के लिए शून्य पास करके, उपयोगकर्ता के पसंद के मुताबिक किए गए दावों को मिटा सकते हैं.

क्लाइंट पर पसंद के मुताबिक दावे लागू करना

एडमिन SDK की मदद से किसी उपयोगकर्ता पर नए दावे होने के बाद, उन्हें क्लाइंट-साइड पर पुष्टि किए गए उपयोगकर्ता को आईडी टोकन के ज़रिए नीचे दिए गए तरीकों से लागू किया जाता है:

  • पसंद के मुताबिक किए गए दावों में बदलाव होने के बाद, उपयोगकर्ता साइन इन करता है या दोबारा पुष्टि करता है. नतीजे के तौर पर जारी किए गए आईडी टोकन में नए दावे शामिल होंगे.
  • पुराने टोकन की समयसीमा खत्म होने के बाद, मौजूदा उपयोगकर्ता सेशन का आईडी टोकन रीफ़्रेश किया जाता है.
  • currentUser.getIdToken(true) को कॉल करने पर, आईडी टोकन को हर हाल में रीफ़्रेश किया जाता है.

क्लाइंट पर अपनी पसंद के मुताबिक किए गए दावों को ऐक्सेस करना

कस्टम दावों को सिर्फ़ उपयोगकर्ता के आईडी टोकन के ज़रिए वापस पाया जा सकता है. उपयोगकर्ता की भूमिका या ऐक्सेस लेवल के हिसाब से, क्लाइंट यूज़र इंटरफ़ेस (यूआई) में बदलाव करने के लिए, इन दावों का ऐक्सेस ज़रूरी हो सकता है. हालांकि, बैकएंड ऐक्सेस को हमेशा आईडी टोकन की मदद से लागू करना चाहिए. ऐसा, इसकी पुष्टि करने और इसके दावों को पार्स करने के बाद किया जाना चाहिए. कस्टम दावों को सीधे बैकएंड पर नहीं भेजा जाना चाहिए, क्योंकि टोकन के अलावा इन पर भरोसा नहीं किया जा सकता.

जब नए दावे उपयोगकर्ता के आईडी टोकन में मिल जाते हैं, तो आईडी टोकन फिर से पाया जा सकता है:

JavaScript

firebase.auth().currentUser.getIdTokenResult()
  .then((idTokenResult) => {
     // Confirm the user is an Admin.
     if (!!idTokenResult.claims.admin) {
       // Show admin UI.
       showAdminUI();
     } else {
       // Show regular user UI.
       showRegularUI();
     }
  })
  .catch((error) => {
    console.log(error);
  });

Android

user.getIdToken(false).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
  @Override
  public void onSuccess(GetTokenResult result) {
    boolean isAdmin = result.getClaims().get("admin");
    if (isAdmin) {
      // Show admin UI.
      showAdminUI();
    } else {
      // Show regular user UI.
      showRegularUI();
    }
  }
});

Swift

user.getIDTokenResult(completion: { (result, error) in
  guard let admin = result?.claims?["admin"] as? NSNumber else {
    // Show regular user UI.
    showRegularUI()
    return
  }
  if admin.boolValue {
    // Show admin UI.
    showAdminUI()
  } else {
    // Show regular user UI.
    showRegularUI()
  }
})

Objective-C

user.getIDTokenResultWithCompletion:^(FIRAuthTokenResult *result,
                                      NSError *error) {
  if (error != nil) {
    BOOL *admin = [result.claims[@"admin"] boolValue];
    if (admin) {
      // Show admin UI.
      [self showAdminUI];
    } else {
      // Show regular user UI.
      [self showRegularUI];
    }
  }
}];

अपने मुताबिक दावे करने के सबसे सही तरीके

कस्टम दावों का इस्तेमाल, सिर्फ़ ऐक्सेस कंट्रोल देने के लिए किया जाता है. इन्हें अतिरिक्त डेटा (जैसे कि प्रोफ़ाइल और अन्य कस्टम डेटा) को स्टोर करने के लिए डिज़ाइन नहीं किया गया है. ऐसा करने के लिए यह एक आसान तरीका लग सकता है, लेकिन हम इसकी सलाह नहीं देते, क्योंकि ये दावे आईडी टोकन में सेव किए जाते हैं. इससे परफ़ॉर्मेंस से जुड़ी समस्याएं हो सकती हैं, क्योंकि पुष्टि किए गए सभी अनुरोधों में हमेशा साइन इन किए हुए उपयोगकर्ता से मिलता-जुलता Firebase आईडी टोकन शामिल होता है.

  • सिर्फ़ उपयोगकर्ताओं के ऐक्सेस को कंट्रोल करने के लिए, डेटा स्टोर करने के लिए कस्टम दावों का इस्तेमाल करें. बाकी सारा डेटा, रीयल-टाइम डेटाबेस या सर्वर साइड स्टोरेज की मदद से अलग से सेव किया जाना चाहिए.
  • कस्टम दावों की संख्या सीमित होती है. अगर पसंद के मुताबिक 1,000 बाइट से ज़्यादा के दावे वाले पेलोड को पास किया जाए, तो आपको गड़बड़ी का मैसेज दिखेगा.

उदाहरण और इस्तेमाल के उदाहरण

नीचे दिए गए उदाहरणों में Firebase के इस्तेमाल के खास मामलों में पसंद के मुताबिक दावे दिखाए गए हैं.

उपयोगकर्ता बनाते समय, Firebase फ़ंक्शन के ज़रिए भूमिकाएं तय करना

इस उदाहरण में, Cloud Functions का इस्तेमाल करके, बनाए जाने पर उपयोगकर्ता पर कस्टम दावे सेट किए गए हैं.

कस्टम दावों को Cloud Functions का इस्तेमाल करके जोड़ा जा सकता है और रीयलटाइम डेटाबेस के साथ तुरंत पेश किया जा सकता है. इस फ़ंक्शन को सिर्फ़ onCreate ट्रिगर का इस्तेमाल करके साइन अप करने पर ही कॉल किया जाता है. कस्टम दावे सेट होने के बाद, ये सभी मौजूदा और आने वाले समय के सेशन में लागू होते हैं. अगली बार जब उपयोगकर्ता उपयोगकर्ता क्रेडेंशियल के साथ साइन इन करता है, तो टोकन में पसंद के मुताबिक दावे शामिल होते हैं.

क्लाइंट-साइड लागू करना (JavaScript)

const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.catch(error => {
  console.log(error);
});

let callback = null;
let metadataRef = null;
firebase.auth().onAuthStateChanged(user => {
  // Remove previous listener.
  if (callback) {
    metadataRef.off('value', callback);
  }
  // On user login add new listener.
  if (user) {
    // Check if refresh is required.
    metadataRef = firebase.database().ref('metadata/' + user.uid + '/refreshTime');
    callback = (snapshot) => {
      // Force refresh to pick up the latest custom claims changes.
      // Note this is always triggered on first call. Further optimization could be
      // added to avoid the initial trigger when the token is issued and already contains
      // the latest claims.
      user.getIdToken(true);
    };
    // Subscribe new listener to changes on that node.
    metadataRef.on('value', callback);
  }
});

Cloud Functions लॉजिक

एक नया डेटाबेस नोड (metadata/($uid)} जोड़ा गया है, जिसमें पुष्टि करने वाले उपयोगकर्ता के लिए पढ़ने/लिखने पर पाबंदी है.

const functions = require('firebase-functions');
const { initializeApp } = require('firebase-admin/app');
const { getAuth } = require('firebase-admin/auth');
const { getDatabase } = require('firebase-admin/database');

initializeApp();

// On sign up.
exports.processSignUp = functions.auth.user().onCreate(async (user) => {
  // Check if user meets role criteria.
  if (
    user.email &&
    user.email.endsWith('@admin.example.com') &&
    user.emailVerified
  ) {
    const customClaims = {
      admin: true,
      accessLevel: 9
    };

    try {
      // Set custom user claims on this newly created user.
      await getAuth().setCustomUserClaims(user.uid, customClaims);

      // Update real-time database to notify client to force refresh.
      const metadataRef = getDatabase().ref('metadata/' + user.uid);

      // Set the refresh time to the current UTC timestamp.
      // This will be captured on the client to force a token refresh.
      await  metadataRef.set({refreshTime: new Date().getTime()});
    } catch (error) {
      console.log(error);
    }
  }
});

डेटाबेस के नियम

{
  "rules": {
    "metadata": {
      "$user_id": {
        // Read access only granted to the authenticated user.
        ".read": "$user_id === auth.uid",
        // Write access only via Admin SDK.
        ".write": false
      }
    }
  }
}

एचटीटीपी अनुरोध के ज़रिए भूमिकाएं तय करना

यहां दिए गए उदाहरण में, एचटीटीपी अनुरोध के ज़रिए साइन इन किए हुए नए उपयोगकर्ता पर, कस्टम उपयोगकर्ता के दावे सेट किए गए हैं.

क्लाइंट-साइड लागू करना (JavaScript)

const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.then((result) => {
  // User is signed in. Get the ID token.
  return result.user.getIdToken();
})
.then((idToken) => {
  // Pass the ID token to the server.
  $.post(
    '/setCustomClaims',
    {
      idToken: idToken
    },
    (data, status) => {
      // This is not required. You could just wait until the token is expired
      // and it proactively refreshes.
      if (status == 'success' && data) {
        const json = JSON.parse(data);
        if (json && json.status == 'success') {
          // Force token refresh. The token claims will contain the additional claims.
          firebase.auth().currentUser.getIdToken(true);
        }
      }
    });
}).catch((error) => {
  console.log(error);
});

बैकएंड को लागू करना (एडमिन SDK)

app.post('/setCustomClaims', async (req, res) => {
  // Get the ID token passed.
  const idToken = req.body.idToken;

  // Verify the ID token and decode its payload.
  const claims = await getAuth().verifyIdToken(idToken);

  // Verify user is eligible for additional privileges.
  if (
    typeof claims.email !== 'undefined' &&
    typeof claims.email_verified !== 'undefined' &&
    claims.email_verified &&
    claims.email.endsWith('@admin.example.com')
  ) {
    // Add custom claims for additional privileges.
    await getAuth().setCustomUserClaims(claims.sub, {
      admin: true
    });

    // Tell client to refresh token on user.
    res.end(JSON.stringify({
      status: 'success'
    }));
  } else {
    // Return nothing.
    res.end(JSON.stringify({ status: 'ineligible' }));
  }
});

किसी मौजूदा उपयोगकर्ता के ऐक्सेस लेवल को अपग्रेड करते समय, इसी फ़्लो का इस्तेमाल किया जा सकता है. उदाहरण के लिए, एक ऐसे उपयोगकर्ता का उदाहरण लें जिसने पैसे चुकाकर सदस्यता ली है. उपयोगकर्ता का आईडी टोकन, क्रेडिट/डेबिट कार्ड की जानकारी के साथ एक एचटीटीपी अनुरोध के ज़रिए बैकएंड सर्वर पर भेजा जाता है. पेमेंट प्रोसेस हो जाने के बाद, एडमिन SDK टूल की मदद से उपयोगकर्ता को, पैसे चुकाकर सदस्यता लेने वाले सदस्य के तौर पर सेट कर दिया जाता है. टोकन रीफ़्रेश करने के लिए, क्लाइंट को एक सफल एचटीटीपी रिस्पॉन्स दिखाया जाता है.

बैकएंड स्क्रिप्ट के ज़रिए भूमिकाएं तय करना

उपयोगकर्ता के कस्टम दावों को अपडेट करने के लिए, बार-बार लागू होने वाली स्क्रिप्ट (क्लाइंट की ओर से शुरू नहीं की गई) को चलाने के लिए सेट किया जा सकता है:

Node.js के लिए

getAuth()
  .getUserByEmail('user@admin.example.com')
  .then((user) => {
    // Confirm user is verified.
    if (user.emailVerified) {
      // Add custom claims for additional privileges.
      // This will be picked up by the user on token refresh or next sign in on new device.
      return getAuth().setCustomUserClaims(user.uid, {
        admin: true,
      });
    }
  })
  .catch((error) => {
    console.log(error);
  });

Java

UserRecord user = FirebaseAuth.getInstance()
    .getUserByEmail("user@admin.example.com");
// Confirm user is verified.
if (user.isEmailVerified()) {
  Map<String, Object> claims = new HashMap<>();
  claims.put("admin", true);
  FirebaseAuth.getInstance().setCustomUserClaims(user.getUid(), claims);
}

Python

user = auth.get_user_by_email('user@admin.example.com')
# Confirm user is verified
if user.email_verified:
    # Add custom claims for additional privileges.
    # This will be picked up by the user on token refresh or next sign in on new device.
    auth.set_custom_user_claims(user.uid, {
        'admin': True
    })

शुरू करें

user, err := client.GetUserByEmail(ctx, "user@admin.example.com")
if err != nil {
	log.Fatal(err)
}
// Confirm user is verified
if user.EmailVerified {
	// Add custom claims for additional privileges.
	// This will be picked up by the user on token refresh or next sign in on new device.
	err := client.SetCustomUserClaims(ctx, user.UID, map[string]interface{}{"admin": true})
	if err != nil {
		log.Fatalf("error setting custom claims %v\n", err)
	}

}

C#

UserRecord user = await FirebaseAuth.DefaultInstance
    .GetUserByEmailAsync("user@admin.example.com");
// Confirm user is verified.
if (user.EmailVerified)
{
    var claims = new Dictionary<string, object>()
    {
        { "admin", true },
    };
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims);
}

कस्टम दावों में, एडमिन SDK टूल की मदद से भी बदलाव किए जा सकते हैं:

Node.js के लिए

getAuth()
  .getUserByEmail('user@admin.example.com')
  .then((user) => {
    // Add incremental custom claim without overwriting existing claims.
    const currentCustomClaims = user.customClaims;
    if (currentCustomClaims['admin']) {
      // Add level.
      currentCustomClaims['accessLevel'] = 10;
      // Add custom claims for additional privileges.
      return getAuth().setCustomUserClaims(user.uid, currentCustomClaims);
    }
  })
  .catch((error) => {
    console.log(error);
  });

Java

UserRecord user = FirebaseAuth.getInstance()
    .getUserByEmail("user@admin.example.com");
// Add incremental custom claim without overwriting the existing claims.
Map<String, Object> currentClaims = user.getCustomClaims();
if (Boolean.TRUE.equals(currentClaims.get("admin"))) {
  // Add level.
  currentClaims.put("level", 10);
  // Add custom claims for additional privileges.
  FirebaseAuth.getInstance().setCustomUserClaims(user.getUid(), currentClaims);
}

Python

user = auth.get_user_by_email('user@admin.example.com')
# Add incremental custom claim without overwriting existing claims.
current_custom_claims = user.custom_claims
if current_custom_claims.get('admin'):
    # Add level.
    current_custom_claims['accessLevel'] = 10
    # Add custom claims for additional privileges.
    auth.set_custom_user_claims(user.uid, current_custom_claims)

शुरू करें

user, err := client.GetUserByEmail(ctx, "user@admin.example.com")
if err != nil {
	log.Fatal(err)
}
// Add incremental custom claim without overwriting existing claims.
currentCustomClaims := user.CustomClaims
if currentCustomClaims == nil {
	currentCustomClaims = map[string]interface{}{}
}

if _, found := currentCustomClaims["admin"]; found {
	// Add level.
	currentCustomClaims["accessLevel"] = 10
	// Add custom claims for additional privileges.
	err := client.SetCustomUserClaims(ctx, user.UID, currentCustomClaims)
	if err != nil {
		log.Fatalf("error setting custom claims %v\n", err)
	}

}

C#

UserRecord user = await FirebaseAuth.DefaultInstance
    .GetUserByEmailAsync("user@admin.example.com");
// Add incremental custom claims without overwriting the existing claims.
object isAdmin;
if (user.CustomClaims.TryGetValue("admin", out isAdmin) && (bool)isAdmin)
{
    var claims = user.CustomClaims.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    // Add level.
    var level = 10;
    claims["level"] = level;
    // Add custom claims for additional privileges.
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims);
}