Geo305
Geo305

Reputation: 1144

Firebase Cloud Messaging - How to validate Tokens?

I am using Firebase Cloud Messaging (FCM) and as per the abreviated code below everytime a new Token is generated on the Customer Device... I send this new TOKEN to my SERVER DB (Cloud) where I save it in order to be able to send future Push Notification from the Server to the Device using the CFM API.

    //public class CFMInstanceIDService extends FirebaseInstanceIdService ...

    public void onTokenRefresh() {
        ...
        String cfmToken = FirebaseInstanceId.getInstance().getToken();        
        ...     
        sendRegistrationToServer(customerGuid, cfmToken);
    }

By doing this I have on the Server a list of ALL (multiples) Devices where a Customer is logged-in. (Tablet, Phone, iPhone, Android, etc)

Is there any way to verify/validate a Token at any time?

I would like to know/ensure that all the tokens that I have associated to a Customer belong to real Devices. I don't want to send Push Notifications to not-existing Tokens.

Upvotes: 60

Views: 60128

Answers (7)

DevLearn123
DevLearn123

Reputation: 31

In the HTTP v1 API, the dry_run flag is now called validate_only.

The docs say validate_only is a:

Flag for testing the request without actually delivering the message.

Upvotes: 3

Tung Luong Thanh
Tung Luong Thanh

Reputation: 473

If you have adminsdk crendeital, you can use this code:

func TestPushToken(t *testing.T) {
    ctx := context.Background()

    opt := option.WithCredentialsJSON([]byte(credential))
    app, err := firebase.NewApp(ctx, nil, opt)
    if err != nil {
        t.Error(err)
    }

    msg := &messaging.Message{
        Notification: &messaging.Notification{
            Title: "Hi",
            Body:  fmt.Sprintf("Welcome at %d", time.Now().Unix()),
        },
        Token: pushToken,
    }

    fcmClient, err := app.Messaging(ctx)
    run, err := fcmClient.SendDryRun(ctx, msg)
    if err != nil {
        t.Error(err)
    }
    fmt.Println(run)
}

If there are any error, that means pushToken is invalid. Or you will get the response like

/messages/fake_message_id

Upvotes: 0

Saud Khan
Saud Khan

Reputation: 844

You can validate the FCM token by calling the

(GET) https://iid.googleapis.com/iid/info/YOUR_APP_TOKEN_HERE
[Header] => 'Authorization: key=YOUR_KEY'

Simple and easy.

If token is valid then it will return 200 status code with some more details in JSON format or if it's invalid then status code will be 400 with error detail in JSON format.

Upvotes: 20

FDG
FDG

Reputation: 800

Actually there is a workaround, you can use dry_run = true

This parameter, when set to true, allows developers to test a request without actually sending a message.

firebase docs

if user unsubscribe, you have a response with NotRegistered but real sending won't be performed

Upvotes: 26

AngularNerd
AngularNerd

Reputation: 991

Here is an example curl request that shows how to validate a token without actually having to send a message:

curl -H "Content-Type: application/json" -H "Authorization: key=$FCM_API_KEY" https://fcm.googleapis.com/fcm/send -d '{"registration_ids":["$FCMTOKEN"]}'

Example invalid response:

{"multicast_id":7452350602151058088,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

Example valid response:

{"multicast_id":9133870199216310277,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1502817580237626%f590ddc2f9fd7ecd"}]}

I got this answer from google's firebase support team.

Upvotes: 51

tyczj
tyczj

Reputation: 73721

No such thing exists, the only information you can get from a token is app information and not wether it is valid or not

https://developers.google.com/instance-id/reference/server#get_information_about_app_instances

what you should be doing is watching for the response when you go to send push's out and if keys are not valid anymore the response will tell you what keys should be deleted withNotRegistered

https://firebase.google.com/docs/cloud-messaging/server

Upvotes: 9

Víctor Albertos
Víctor Albertos

Reputation: 8293

There is no way to validate if a token is still valid prior to send the downstream message. What you need to do is to check the response after sending the message and then check if the response contains any error.

For example, if the server returns an 200 + error:NotRegistered http code, it means that an existing registration token may cease to be valid.

In the section "Downstream message error response codes of FGC", you will find documented every possible status response.

Upvotes: 2

Related Questions