Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Cloud Messaging Server Account key expires

So I have an app which requires the Firebase Service Account Key. As stated in the documentation, it is a short lived key. So do I need to manually keep downloading the Service Account Key JSON file every time it expires?

1.This is the code I am using to extract the token from the JSON file.

SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
def _get_access_token():
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        '{valid_path/file.json}', SCOPES)
    access_token_info = credentials.get_access_token()
    return access_token_info.access_token

2.The link is : https://fcm.googleapis.com/v1/projects/{valid_project_id}/messages:send

3.Content-Type : application/json; UTF-8

4.Authorization : Bearer *access_token_returned_in_step_1*

5.Body

{
   "message":{
      "name":"name_field",
      "android":{
         "ttl":"81000s",
         "data":{
            "Name":"Z",
            "Surname":"Z"
         },
         "notification":{
            "title":"Hello",
            "body":"World"
         }
      },
      "topic":"test_topic"
   }
}

6. Works perfectly well for some time. And then,

{
   "error":{
      "code":401,
      "message":"Request had invalid authentication credentials. 
    Expected OAuth 2 access token, login cookie or other valid 
    authentication credential. See 
    https://developers.google.com/identity/sign-in/web/devconsole- 
   project.",
      "status":"UNAUTHENTICATED"
   }
}

7. When I download the Service Account Key JSON file again and run the same procedure again, it works.

So, is there a way around manually downloading the Service Account Key JSON file?

like image 953
magnum_skrattar Avatar asked Sep 06 '25 03:09

magnum_skrattar


1 Answers

I was reusing the access token extracted from the service_account.json file and pasting it into Postman for testing purposes. That was the issue. The token needs to be generated every time one needs to send messages via FCM. So, step 1 ie. _get_access_token() needs to be executed every time before sending an FCM notification / data message. Step 1 must be communicating with FCM to retrieve the latest valid token.

like image 54
magnum_skrattar Avatar answered Sep 07 '25 19:09

magnum_skrattar