user8207330
user8207330

Reputation:

How to get OAuth2.0 Token for Firebase Cloud Messaging

I have set up my web app to receive Firebase Cloud Messages, but in order to send them I understand that I need an OAuth2.0 Token, which is generated from my Service Account private key. I have downloaded the key and installed Google API Client Library for Python. This is my code:

from oauth2client import *
def _get_access_token():
  """Retrieve a valid access token that can be used to authorize requests.

  :return: Access token.
  """
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      'service-account.json', FCM_SCOPE)
  access_token_info = credentials.get_access_token()
  return access_token_info.access_token

_get_access_token()

When I run that, I get

Traceback (most recent call last):
  File "get-oauth-token.py", line 11, in <module>
    _get_access_token()
  File "get-oauth-token.py", line 7, in _get_access_token
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
NameError: name 'ServiceAccountCredentials' is not defined

I assume that I'm missing an import, but I'm not sure what.

Upvotes: 3

Views: 2172

Answers (1)

jiamo
jiamo

Reputation: 1456

This should solve:

from oauth2client.service_account import ServiceAccountCredentials
fsm_scope = 'https://www.googleapis.com/auth/firebase.messaging'

def _get_access_token():
    """Retrieve a valid access token that can be used to authorize requests.

    :return: Access token.
    """
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'service-account.json', fsm_scope)
    access_token_info = credentials.get_access_token()
    return access_token_info.access_token

_get_access_token()

Upvotes: 6

Related Questions