कस्टम दावों और सुरक्षा नियमों के साथ पहुंच को नियंत्रित करें

फायरबेस एडमिन एसडीके उपयोगकर्ता खातों पर कस्टम विशेषताओं को परिभाषित करने का समर्थन करता है। यह फायरबेस ऐप्स में भूमिका-आधारित एक्सेस नियंत्रण सहित विभिन्न एक्सेस कंट्रोल रणनीतियों को लागू करने की क्षमता प्रदान करता है। ये कस्टम विशेषताएँ उपयोगकर्ताओं को विभिन्न स्तरों तक पहुंच (भूमिकाएं) दे सकती हैं, जो किसी एप्लिकेशन के सुरक्षा नियमों में लागू होती हैं।

निम्नलिखित सामान्य मामलों के लिए उपयोगकर्ता भूमिकाएँ परिभाषित की जा सकती हैं:

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

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

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

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

इस पृष्ठ में वर्णित कोड उदाहरण और समाधान क्लाइंट-साइड फ़ायरबेस ऑथ एपीआई और एडमिन एसडीके द्वारा प्रदान किए गए सर्वर-साइड ऑथ एपीआई दोनों से लिए गए हैं।

व्यवस्थापक SDK के माध्यम से कस्टम उपयोगकर्ता दावों को सेट और मान्य करें

कस्टम दावों में संवेदनशील डेटा हो सकता है, इसलिए उन्हें केवल फ़ायरबेस एडमिन एसडीके द्वारा विशेषाधिकार प्राप्त सर्वर वातावरण से सेट किया जाना चाहिए।

नोड.जे.एस

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

जावा

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

अजगर

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

सी#

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

कस्टम दावा ऑब्जेक्ट में कोई ओआईडीसी आरक्षित कुंजी नाम या फायरबेस आरक्षित नाम नहीं होना चाहिए। कस्टम दावा पेलोड 1000 बाइट्स से अधिक नहीं होना चाहिए।

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

नोड.जे.एस

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

जावा

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

अजगर

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

सी#

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

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

नोड.जे.एस

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

जावा

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

अजगर

# 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)
	}
}

सी#

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

आप customClaims के लिए null पास करके उपयोगकर्ता के कस्टम दावों को हटा सकते हैं।

ग्राहक तक कस्टम दावों का प्रचार करें

एडमिन एसडीके के माध्यम से किसी उपयोगकर्ता पर नए दावों को संशोधित करने के बाद, उन्हें निम्नलिखित तरीकों से आईडी टोकन के माध्यम से क्लाइंट पक्ष पर एक प्रमाणित उपयोगकर्ता तक प्रचारित किया जाता है:

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

क्लाइंट पर कस्टम दावों तक पहुंचें

कस्टम दावे केवल उपयोगकर्ता के आईडी टोकन के माध्यम से प्राप्त किए जा सकते हैं। उपयोगकर्ता की भूमिका या पहुंच स्तर के आधार पर क्लाइंट यूआई को संशोधित करने के लिए इन दावों तक पहुंच आवश्यक हो सकती है। हालाँकि, बैकएंड एक्सेस को हमेशा आईडी टोकन के माध्यम से मान्य करने और उसके दावों को पार्स करने के बाद लागू किया जाना चाहिए। कस्टम दावों को सीधे बैकएंड पर नहीं भेजा जाना चाहिए, क्योंकि टोकन के बाहर उन पर भरोसा नहीं किया जा सकता है।

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

जावास्क्रिप्ट

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);
  });

एंड्रॉयड

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();
    }
  }
});

तीव्र

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()
  }
})

उद्देश्य सी

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];
    }
  }
}];

कस्टम दावों के लिए सर्वोत्तम अभ्यास

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

  • केवल उपयोगकर्ता पहुंच को नियंत्रित करने के लिए डेटा संग्रहीत करने के लिए कस्टम दावों का उपयोग करें। अन्य सभी डेटा को वास्तविक समय डेटाबेस या अन्य सर्वर साइड स्टोरेज के माध्यम से अलग से संग्रहीत किया जाना चाहिए।
  • कस्टम दावे आकार में सीमित हैं. 1000 बाइट्स से अधिक कस्टम दावा पेलोड पास करने पर एक त्रुटि आएगी।

उदाहरण और उपयोग के मामले

निम्नलिखित उदाहरण विशिष्ट फायरबेस उपयोग मामलों के संदर्भ में कस्टम दावों को दर्शाते हैं।

उपयोगकर्ता निर्माण पर फायरबेस फ़ंक्शंस के माध्यम से भूमिकाएँ परिभाषित करना

इस उदाहरण में, क्लाउड फ़ंक्शंस का उपयोग करके निर्माण पर उपयोगकर्ता पर कस्टम दावे सेट किए जाते हैं।

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

क्लाइंट साइड कार्यान्वयन (जावास्क्रिप्ट)

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);
  }
});

क्लाउड फ़ंक्शंस तर्क

प्रमाणित उपयोगकर्ता तक सीमित पढ़ने/लिखने के साथ एक नया डेटाबेस नोड (मेटाडेटा/($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
      }
    }
  }
}

HTTP अनुरोध के माध्यम से भूमिकाएँ परिभाषित करना

निम्नलिखित उदाहरण HTTP अनुरोध के माध्यम से नए साइन इन किए गए उपयोगकर्ता पर कस्टम उपयोगकर्ता दावे सेट करता है।

क्लाइंट साइड कार्यान्वयन (जावास्क्रिप्ट)

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);
});

बैकएंड कार्यान्वयन (व्यवस्थापक एसडीके)

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

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

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

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

नोड.जे.एस

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);
  });

जावा

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);
}

अजगर

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

}

सी#

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 के माध्यम से क्रमिक रूप से संशोधित भी किया जा सकता है:

नोड.जे.एस

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);
  });

जावा

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);
}

अजगर

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

}

सी#

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 = new Dictionary<string, object>(user.CustomClaims);
    // Add level.
    claims["level"] = 10;
    // Add custom claims for additional privileges.
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims);
}