Firebase is a service-based mobile and web development platform that provides lots of services like messaging, push notifications, cloud storage, authentication, real-time database, and much more. To use these functionalities, firebase API requires an Authorization or Bearer token.
This Authorization token, also called “oauth2 Token,” needs to be generated through backend languages like Python, Java, nodeJS, etc…
Here, we are going to take a look at a few steps in python to generate an oauth2 token which will be helpful to use Firebase V1 API.
Generate Firebase V1 API Token
Note: You must have a google firebase account first. If you don’t have one, you can sign up here https://firebase.google.com
As this post is all about Firebase Token Generation in Python, so I hope you all are aware of the firebase console.
Step 1: Install oauth2client and requests library
You need to install oauth2client dependency to use google APIs in python and also requests to make a request in python.
You can install them in python with the below code.
pip install requests
pip install oauth2client
Note: You need to use Sudo if you get a user permission issue.
Step 2: Create a service-account.json File
We need to create a service-account.json file, which holds all the information about our firebase project. It looks like the below example.
"private_key": "---BEGIN PRIVATE KEY---\n[PRIVATE-KEY]\n---END PRIVATE KEY---\n",
We can simply replace the dummy data with our project credentials. You can also directly download the file here https://console.cloud.google.com/project/_/iam-admin
Follow the below steps to generate service-account.json file
- Open https://console.cloud.google.com/project/_/iam-admin
- Select project and click continue
- From left navigation select Service Accounts
- Select an email account and click on the Action button at right in that row, and click on Create key.
- Select JSON, and it’s done. The service-account.json file will be downloaded automatically.
- Move the service-account.json file to your project directory.
Step 3: Code to Generate oauth2/Bearer/Authentication Token
Copy and paste below function in your python project and generate a token by calling function.
from oauth2client.service_account import ServiceAccountCredentials
PROJECT_ID = '<--YOUR PROJECT_ID-->'
BASE_URL = 'https://fcm.googleapis.com'
FCM_ENDPOINT = 'v1/projects/' + PROJECT_ID + '/messages:send'
FCM_URL = BASE_URL + '/' + FCM_ENDPOINT
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
credentials = ServiceAccountCredentials.from_json_keyfile_name('<-- PATH TO service-account.json FILE', SCOPES)
access_token_info = credentials.get_access_token()
Note: Please don’t forget to replace PROJECT_ID and PATH to the service-account.json file.
I hope you found this post informative.
Enjoy Programming 🙂