उपयोगकर्ता के सेशन को मैनेज करें

Firebase से पुष्टि करने वाले सेशन लंबे समय तक चलते हैं. जब भी कोई उपयोगकर्ता साइन इन करता है, तो उपयोगकर्ता के क्रेडेंशियल, Firebase से पुष्टि करने वाले बैकएंड को भेजे जाते हैं. साथ ही, उन्हें Firebase आईडी टोकन (JWT) और रीफ़्रेश टोकन से एक्सचेंज किया जाता है. Firebase आईडी टोकन कम समय तक चलते हैं और ये एक घंटे तक चलते हैं. रीफ़्रेश टोकन का इस्तेमाल करके, नया आईडी टोकन पाया जा सकता है. रीफ़्रेश टोकन की समयसीमा सिर्फ़ तब खत्म होती है, जब इनमें से कोई एक समस्या होती है:

  • उपयोगकर्ता को मिटा दिया गया है
  • उपयोगकर्ता अक्षम है
  • उपयोगकर्ता के खाते में किसी बड़े बदलाव का पता चलता है. इसमें पासवर्ड या ईमेल पता अपडेट करने जैसे इवेंट शामिल हैं.

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

रीफ़्रेश टोकन रद्द करें

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

पासवर्ड रीसेट होने की वजह से, उपयोगकर्ता के मौजूदा टोकन भी रद्द कर दिए जाते हैं. हालांकि, ऐसे मामले में Firebase से पुष्टि करने वाला बैकएंड, रद्द करने की प्रक्रिया को अपने-आप मैनेज करता है. निरस्त करने पर, उपयोगकर्ता को साइन आउट कर दिया जाता है और फिर से पुष्टि करने के लिए कहा जाता है.

यहां एक उदाहरण दिया गया है, जिसमें किसी उपयोगकर्ता के रीफ़्रेश टोकन को रद्द करने के लिए, एडमिन SDK टूल का इस्तेमाल किया जाता है. 'एडमिन SDK' इस्तेमाल करने के लिए, सेटअप पेज पर दिए गए निर्देशों का पालन करें.

Node.js के लिए

// Revoke all refresh tokens for a specified user for whatever reason.
// Retrieve the timestamp of the revocation, in seconds since the epoch.
getAuth()
  .revokeRefreshTokens(uid)
  .then(() => {
    return getAuth().getUser(uid);
  })
  .then((userRecord) => {
    return new Date(userRecord.tokensValidAfterTime).getTime() / 1000;
  })
  .then((timestamp) => {
    console.log(`Tokens revoked at: ${timestamp}`);
  });

Java

FirebaseAuth.getInstance().revokeRefreshTokens(uid);
UserRecord user = FirebaseAuth.getInstance().getUser(uid);
// Convert to seconds as the auth_time in the token claims is in seconds too.
long revocationSecond = user.getTokensValidAfterTimestamp() / 1000;
System.out.println("Tokens revoked at: " + revocationSecond);

Python

# Revoke tokens on the backend.
auth.revoke_refresh_tokens(uid)
user = auth.get_user(uid)
# Convert to seconds as the auth_time in the token claims is in seconds.
revocation_second = user.tokens_valid_after_timestamp / 1000
print('Tokens revoked at: {0}'.format(revocation_second))

शुरू करें

client, err := app.Auth(ctx)
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}
if err := client.RevokeRefreshTokens(ctx, uid); err != nil {
	log.Fatalf("error revoking tokens for user: %v, %v\n", uid, err)
}
// accessing the user's TokenValidAfter
u, err := client.GetUser(ctx, uid)
if err != nil {
	log.Fatalf("error getting user %s: %v\n", uid, err)
}
timestamp := u.TokensValidAfterMillis / 1000
log.Printf("the refresh tokens were revoked at: %d (UTC seconds) ", timestamp)

C#

await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(uid);
var user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid);
Console.WriteLine("Tokens revoked at: " + user.TokensValidAfterTimestamp);

आईडी टोकन निरस्त करने का पता लगाएं

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

Firebase के सुरक्षा नियमों में, आईडी टोकन रद्द होने का पता लगाएं

सुरक्षा के नियमों का इस्तेमाल करके आईडी टोकन रद्द होने का पता लगाने के लिए, हमें सबसे पहले कुछ खास उपयोगकर्ता का मेटाडेटा सेव करना होगा.

Firebase रीयल टाइम डेटाबेस में, उपयोगकर्ता के हिसाब से बना मेटाडेटा अपडेट करें.

रीफ़्रेश टोकन रद्द करने के टाइमस्टैंप को सेव करें. Firebase सुरक्षा नियमों के ज़रिए आईडी टोकन रद्द होने को ट्रैक करने के लिए यह ज़रूरी है. इससे डेटाबेस में, बेहतर तरीके से जांच करने में मदद मिलती है. नीचे दिए गए कोड सैंपल में, uid और पिछले सेक्शन में दिए गए सहमति रद्द करने के समय का इस्तेमाल करें.

Node.js के लिए

const metadataRef = getDatabase().ref('metadata/' + uid);
metadataRef.set({ revokeTime: utcRevocationTimeSecs }).then(() => {
  console.log('Database updated successfully.');
});

Java

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("metadata/" + uid);
Map<String, Object> userData = new HashMap<>();
userData.put("revokeTime", revocationSecond);
ref.setValueAsync(userData);

Python

metadata_ref = firebase_admin.db.reference("metadata/" + uid)
metadata_ref.set({'revokeTime': revocation_second})

Firebase के सुरक्षा नियम में सही का निशान लगाएं

इस जांच को लागू करने के लिए, ऐसा नियम सेट अप करें जिसके पास क्लाइंट राइट ऐक्सेस न हो, ताकि हर उपयोगकर्ता के लिए निरस्त करने का समय स्टोर किया जा सके. इसे पिछले उदाहरणों में दिखाए गए तरीके से, पिछली बार रद्द करने के समय के यूटीसी टाइमस्टैंप की मदद से अपडेट किया जा सकता है:

{
  "rules": {
    "metadata": {
      "$user_id": {
        // this could be false as it is only accessed from backend or rules.
        ".read": "$user_id === auth.uid",
        ".write": "false",
      }
    }
  }
}

जिस डेटा के लिए पुष्टि किए गए ऐक्सेस की ज़रूरत होती है उसके लिए, नीचे दिए गए नियम कॉन्फ़िगर होने चाहिए. यह लॉजिक, पुष्टि किए गए उन उपयोगकर्ताओं को ही सुरक्षित डेटा ऐक्सेस करने की अनुमति देता है जिनके पास रद्द नहीं किए गए आईडी टोकन हैं:

{
  "rules": {
    "users": {
      "$user_id": {
        ".read": "auth != null && $user_id === auth.uid && (
            !root.child('metadata').child(auth.uid).child('revokeTime').exists()
          || auth.token.auth_time > root.child('metadata').child(auth.uid).child('revokeTime').val()
        )",
        ".write": "auth != null && $user_id === auth.uid && (
            !root.child('metadata').child(auth.uid).child('revokeTime').exists()
          || auth.token.auth_time > root.child('metadata').child(auth.uid).child('revokeTime').val()
        )",
      }
    }
  }
}

SDK टूल में आईडी टोकन के निरस्त होने का पता लगाएं.

अपने सर्वर में, रीफ़्रेश टोकन रद्द करने और आईडी टोकन की पुष्टि करने के लिए, यह लॉजिक लागू करें:

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

अपने प्लैटफ़ॉर्म के लिए एडमिन SDK टूल शुरू करने के लिए, सेटअप पेज पर दिए गए निर्देशों का पालन करें. आईडी टोकन को फिर से पाने के उदाहरण verifyIdToken सेक्शन में दिए गए हैं.

Node.js के लिए

// Verify the ID token while checking if the token is revoked by passing
// checkRevoked true.
let checkRevoked = true;
getAuth()
  .verifyIdToken(idToken, checkRevoked)
  .then((payload) => {
    // Token is valid.
  })
  .catch((error) => {
    if (error.code == 'auth/id-token-revoked') {
      // Token has been revoked. Inform the user to reauthenticate or signOut() the user.
    } else {
      // Token is invalid.
    }
  });

Java

try {
  // Verify the ID token while checking if the token is revoked by passing checkRevoked
  // as true.
  boolean checkRevoked = true;
  FirebaseToken decodedToken = FirebaseAuth.getInstance()
      .verifyIdToken(idToken, checkRevoked);
  // Token is valid and not revoked.
  String uid = decodedToken.getUid();
} catch (FirebaseAuthException e) {
  if (e.getAuthErrorCode() == AuthErrorCode.REVOKED_ID_TOKEN) {
    // Token has been revoked. Inform the user to re-authenticate or signOut() the user.
  } else {
    // Token is invalid.
  }
}

Python

try:
    # Verify the ID token while checking if the token is revoked by
    # passing check_revoked=True.
    decoded_token = auth.verify_id_token(id_token, check_revoked=True)
    # Token is valid and not revoked.
    uid = decoded_token['uid']
except auth.RevokedIdTokenError:
    # Token revoked, inform the user to reauthenticate or signOut().
    pass
except auth.UserDisabledError:
    # Token belongs to a disabled user record.
    pass
except auth.InvalidIdTokenError:
    # Token is invalid
    pass

शुरू करें

client, err := app.Auth(ctx)
if err != nil {
	log.Fatalf("error getting Auth client: %v\n", err)
}
token, err := client.VerifyIDTokenAndCheckRevoked(ctx, idToken)
if err != nil {
	if err.Error() == "ID token has been revoked" {
		// Token is revoked. Inform the user to reauthenticate or signOut() the user.
	} else {
		// Token is invalid
	}
}
log.Printf("Verified ID token: %v\n", token)

C#

try
{
    // Verify the ID token while checking if the token is revoked by passing checkRevoked
    // as true.
    bool checkRevoked = true;
    var decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(
        idToken, checkRevoked);
    // Token is valid and not revoked.
    string uid = decodedToken.Uid;
}
catch (FirebaseAuthException ex)
{
    if (ex.AuthErrorCode == AuthErrorCode.RevokedIdToken)
    {
        // Token has been revoked. Inform the user to re-authenticate or signOut() the user.
    }
    else
    {
        // Token is invalid.
    }
}

क्लाइंट पर टोकन निरस्त होने पर जवाब दें

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

function onIdTokenRevocation() {
  // For an email/password user. Prompt the user for the password again.
  let password = prompt('Please provide your password for reauthentication');
  let credential = firebase.auth.EmailAuthProvider.credential(
      firebase.auth().currentUser.email, password);
  firebase.auth().currentUser.reauthenticateWithCredential(credential)
    .then(result => {
      // User successfully reauthenticated. New ID tokens should be valid.
    })
    .catch(error => {
      // An error occurred.
    });
}

बेहतर सुरक्षा: आईपी पते से जुड़ी पाबंदियां लागू करें

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

हर पुष्टि किए गए अनुरोध के लिए, आईपी पते के आधार पर सुरक्षा जांच करने के लिए, आईडी टोकन की जांच करें. साथ ही, यह देखें कि सीमित डेटा का ऐक्सेस देने से पहले, अनुरोध का आईपी पता पिछले भरोसेमंद आईपी पतों से मेल खाता है या नहीं. उदाहरण के लिए:

app.post('/getRestrictedData', (req, res) => {
  // Get the ID token passed.
  const idToken = req.body.idToken;
  // Verify the ID token, check if revoked and decode its payload.
  admin.auth().verifyIdToken(idToken, true).then((claims) => {
    // Get the user's previous IP addresses, previously saved.
    return getPreviousUserIpAddresses(claims.sub);
  }).then(previousIpAddresses => {
    // Get the request IP address.
    const requestIpAddress = req.connection.remoteAddress;
    // Check if the request IP address origin is suspicious relative to previous
    // IP addresses. The current request timestamp and the auth_time of the ID
    // token can provide additional signals of abuse especially if the IP address
    // suddenly changed. If there was a sudden location change in a
    // short period of time, then it will give stronger signals of possible abuse.
    if (!isValidIpAddress(previousIpAddresses, requestIpAddress)) {
      // Invalid IP address, take action quickly and revoke all user's refresh tokens.
      revokeUserTokens(claims.uid).then(() => {
        res.status(401).send({error: 'Unauthorized access. Please login again!'});
      }, error => {
        res.status(401).send({error: 'Unauthorized access. Please login again!'});
      });
    } else {
      // Access is valid. Try to return data.
      getData(claims).then(data => {
        res.end(JSON.stringify(data);
      }, error => {
        res.status(500).send({ error: 'Server error!' })
      });
    }
  });
});