11

I am getting the FCM first time and save it to my userDefaults. Now When user logs out, how can I refresh the FCM token again? I have searched the docs and many other asked questions, but didn't find a better solution.

Thanks in advance.

AL.
  • 36,815
  • 10
  • 142
  • 281
Nivesh
  • 201
  • 1
  • 3
  • 13

3 Answers3

35

The FCM Token is an Instance ID token, it represents the installed app and not the signed in user. Generally once the app remains installed it will have the same token no matter what user is signed in.

You would have to manage what user is associated to the token yourself. When the user signs in you should associate the token with the user's ID and when the user signs out you should remove that association.

Arthur Thompson
  • 9,087
  • 4
  • 29
  • 33
8

To get a new refreshed FCM token (forcefully), first you have to delete it and then request for FCM token again. It will always provide a new token after once deletion.

To delete a saved token:

FirebaseMessaging.getInstance().deleteToken()

To request a FCM token:

        Firebase.messaging.isAutoInitEnabled = true
        // Get token
        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            //On token fetch fail
            if (!task.isSuccessful) {
               //msg_token_failed
                Log.e("Token failed", task.exception)
                return@OnCompleteListener
            }

            // Get new Instance ID token
            val newDeviceToken = task.result
            Log.e("newDeviceToken", newDeviceToken)
        })

So, in your case you can delete FCM token on logout and request it again on login. It will work.

Ready Android
  • 3,529
  • 2
  • 26
  • 40
0

Check this post: Firebase Cloud Messaging - Handling logout

Mentioned security issue in @Arthur's comment is solved!

Reza Roshan
  • 147
  • 3
  • 7