如何使“过期"的Firebase实例ID令牌无效 [英] How to invalidate 'expired' Firebase Instance ID Token

查看:221
本文介绍了如何使“过期"的Firebase实例ID令牌无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,Firebase实例令牌将在以下4种情况下刷新:

AFAIK, the Firebase Instance Token will be refreshed under the following 4 conditions:

  1. 应用程序删除实例ID

  1. App deletes Instance ID

应用已在新设备上还原

用户卸载/重新安装应用程序

User uninstalls/reinstall the app

用户清除应用数据

假设用户使用令牌A作为其"FCM地址".每次登录该应用程序时,他都会将令牌A与该用户的UUID一起注册到Firestore中,以便可以将特定于用户的云消息发送给他.他注销后,系统将向Firestore发出删除令牌A记录的请求.

Suppose a user is using Token A as his 'FCM address'. Every time when he logs in the app, he will register the Token A to the Firestore along with this user's UUID so user-specific cloud message can be sent to him. When he logs out, the system will fire a request to firestore for removing the token A record.

现在,当用户重新安装应用程序时,实例ID会刷新并生成新的令牌B.令牌A变得无用.不幸的是,如果用户在卸载前未注销,则令牌A将永远留在Firestore中.

Now, when the user reinstalls the app, the instance id is refreshed and a new Token B is generated. The Token A becomes useless. Unfortunately, if the user does not log out before the uninstallation, token A will stay in the firestore forever.

有什么解决方法或更明智的方式来处理这种情况?

Any workaround or wiser way to handle this case?

推荐答案

使令牌注册表保持最新状态需要两个步骤:

Keeping your token registry up to date requires two steps:

  1. 从应用程序代码中删除过时的令牌.
  2. 检查过时的令牌,并在发送消息时将其删除.
  1. Remove outdated tokens from your application code.
  2. Check for outdated tokens and remove them when you send messages.

您的删除不再使用的令牌的方法是#1.

Your approach of removing a token that is no longer used, is #1.

第二步是在尝试向其发送消息时收到messaging/invalid-registration-tokenmessaging/registration-token-not-registered响应时,从注册表/数据库中删除令牌. functions-samples回购包含一个很好的例子:

The second step though is to remove tokens from your registry/database when you get a messaging/invalid-registration-token or messaging/registration-token-not-registered response when trying to send a message to it. The functions-samples repo contains a great example of this:

admin.messaging().sendToDevice(tokens, payload).then((response) => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        // TODO: remove the token from your registry/database
      }
    }
  });
});

以上代码使用了用于Node.js的Firebase Admin SDK,但相同的逻辑也可以应用于其他平台或通过HTTPS端点发送消息时.

The above code uses the Firebase Admin SDK for Node.js, but the same logic could also be applied to other platforms or when sending messages through the HTTPS endpoints.

这篇关于如何使“过期"的Firebase实例ID令牌无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆