Get an Access Token for your service account with the Firebase Admin Python SDK

Postscript

Firebase Admin Python SDK v2.0.0 was released on May 17, 2017, and some calling methods were different, so I added it as a supplement.

Overview

On April 4, 2017 (around 4/5 early morning in Japan time), the Firebase SDK for Python was released by Google officially. The official name is "Firebase Admin Python SDK", and as the name suggests, it is an SDK that supports APIs around Admin.

Release Notes  |  Firebase

What you can do with the Firebase Admin Python SDK

As the name suggests (second time), processing around Admin is provided. However, when I read the reference and guide, it seems that the function currently provided is "only the part that creates a Custom Token or Access Token from the private key of the service account".

How to use

Add the Firebase Admin SDK to your Server  |  Firebase

I will trace the contents written above as it is, but be careful as it will be clogged if it is ** as it is **.

First of all, get the private key. Open the project from the Firebase console site (https://console.firebase.com/), go to Gear> Project Settings> Service Account next to Overview in the menu, and click "New Private Key" at the bottom of the screen. Press the "Generate" button to get the json file.

Then install the required libraries with pip.

$ pip install firebase-admin

The code looks like this.

v1.0.0

getToken.py



import firebase_admin
from firebase_admin import credentials

def getToken:

    credential = credentials.Certificate('./serviceAccountKey.json')
    scopes = [
        'https://www.googleapis.com/auth/firebase.database',
        'https://www.googleapis.com/auth/userinfo.email'
    ]

    # access_Get token
    accessTokenInfo = credential.get_credential().create_scoped(scopes).get_access_token()
    print("access_token:" + accessTokenInfo.access_token)
    print("expire:" + str(accessTokenInfo.expires_in))

if __name__ == '__main__':
    getToken()

The difference from the official document is that you can set the scope to credential without using firebase_admin.initialize_app () and get the AccessToken as it is.

v2.0.0

getToken.py


import firebase_admin
from firebase_admin import credentials

def getToken:

    credential = credentials.Certificate('./serviceAccountKey.json')

    # access_Get token
    accessTokenInfo = credential.get_access_token()
    print("access_token:" + accessTokenInfo.access_token)
    print("expire:" + str(accessTokenInfo.expiry)) # 「20XX-XX-XX XX:XX:XX.XXXXXX "is returned

if __name__ == '__main__':
    getToken()

The difference from v1.0.0 is that you no longer need to get the credential information once with get_credential () or set the scope. Also, while the content of the expiration date was the number of seconds remaining in v1.0.0, from v2.0.0 the property name is ʻexpiry`, and the available expiration date is returned as a datetime object. I will.

Access Realtime Database with the acquired token

When using with RealtimeDatabase, you can access it by putting it in the parameter ʻaccess_token`. Since this AccessToken is created by a service account, it is possible to read and write even if all users are false in the database rules, so be careful when handling it. ** By the way, the token is valid for 1 hour after issuance.

https://{FIREBASE_PROJECT_ID}.firebaseio.com/hoge.json?access_token={FIREBASE_ACCESS_TOKEN}

I think that you can get a CustomToken in the same way, but when you get an AccessToken correctly, it is no longer necessary for you, so it remains unverified.

Recommended Posts

Get an Access Token for your service account with the Firebase Admin Python SDK
Get an access token for the Pocket API
[For beginners] Web scraping with Python "Access the URL in the page to get the contents"
Create a Twitter BOT with the GoogleAppEngine SDK for Python
[Python] Get the script execution directory with an absolute path
Get the weather with Python requests
Get the weather with Python requests 2
Grant an access token with the curl command and POST the API
[Cloudian # 1] Try to access object storage with AWS SDK for Python (boto3)
Get the return value of an external shell script (ls) with python3
How to access data with object ['key'] for your own Python class
Get an access token by OAuth authentication
[Python] Get the variable name with str
Working with OpenStack using the Python SDK
Register users with Google Admin SDK (python)
Get a token for conoha in python
Crawl Follower for an account with Instagram
How to use Service Account OAuth and API with Google API Client for python
The road to updating Splunkbase with your own Splunk app for Python v2 / v3
Create a filter to get an Access Token in the Graph API (Flask)
[Introduction to Python] How to get the index of data with a for statement
[Python] Get the files in a folder with Python
Get a ticket for a theme park with python
[Python] matplotlib: Format the diagram for your dissertation
Building an Anaconda environment for Python with pyenv
Upgrade the Azure Machine Learning SDK for Python
Use logger with Python for the time being
Get note information using Evernote SDK for Python 3
[Python] Predict the appropriate rent for an apartment
Call Polly from the AWS SDK for Python
For those who should have installed janome properly with Python but get an error
Make your python CUI application an app for mac
Learn Service Bus Queue with Azure SDK for Go (1)
Run with CentOS7 + Apache2.4 + Python3.6 for the time being
Fleet provisioning with AWS IoT SDK for Python v2
[Python] Get the numbers in the graph image with OCR
Users without an account access the AWS Management Console
Get the result in dict format with Python psycopg2
Information for controlling the motor with Python on RaspberryPi
Building an environment for natural language processing with Python
Python: Get a list of methods for an object
Get the operation status of JR West with Python
Get data from database via ODBC with Python (Access)
Programming with your smartphone anywhere! (Recommended for C / Python)
Access Google Cloud Storage from Python (boto) using your service account and key file (p12)
How to get the information of organizations, Cost Explorer of another AWS account with Lambda (python)