Authenticate REST Requests  |  Firebase Realtime Database (2024)

Stay organized with collections Save and categorize content based on your preferences.

The Firebase SDKs handle all authentication and communication with theFirebase Realtime Database on your behalf. However, when you're in anenvironment that doesn't have a client SDK or you want to avoid the overhead ofa persistent database connection, you can make use of theRealtime Database REST API to read and write data.

Authenticate users through one of the following methods:

  1. Google OAuth2 access tokens - Typically, the ability to read from andwrite to the Realtime Database is governed byRealtime Database Rules. But, you can access your datafrom a server and grant that server full read and write access to yourdata with a Google OAuth2 access token generated from a service account.

  2. Firebase ID tokens - You might also want to send requests authenticatedas an individual user, like limiting access with Realtime Database Rules on theclient SDKs. The REST API accepts the same Firebase ID tokens used by theclient SDKs.

Google OAuth2 access tokens

Any data that's publicly readable or writable according to yourRealtime Database Rules is also readable and writablevia the REST API without any authentication. However, if you want your serverto bypass your Realtime Database Rules, you need to authenticate your read and writerequests. Authentication through Google OAuth2 requires the following steps:

  1. Generate an access token.
  2. Authenticate with that access token.

Generate an access token

The Realtime Database REST API acceptsstandardGoogle OAuth2 access tokens.The access tokens can be generated using a service account with properpermissions to your Realtime Database. Clicking the Generate New PrivateKey button at the bottom of theService Accountssection of the Firebase console allows you to easily generate a new serviceaccount key file if you do not have one already.

Once you have a service account key file, you can use one of theGoogle API client librariesto generate a Google OAuth2 access token with the following required scopes:

  • https://www.googleapis.com/auth/userinfo.email
  • https://www.googleapis.com/auth/firebase.database

Here are some example implementations that show how to create Google OAuth2access tokens to authenticate to the Realtime Database REST APIin a variety of languages:

Node.js

Using the Google API Client Library forNode.js:

var {google} = require("googleapis");// Load the service account key JSON file.var serviceAccount = require("path/to/serviceAccountKey.json");// Define the required scopes.var scopes = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/firebase.database"];// Authenticate a JWT client with the service account.var jwtClient = new google.auth.JWT( serviceAccount.client_email, null, serviceAccount.private_key, scopes);// Use the JWT client to generate an access token.jwtClient.authorize(function(error, tokens) { if (error) { console.log("Error making request to generate access token:", error); } else if (tokens.access_token === null) { console.log("Provided service account does not have permission to generate access tokens"); } else { var accessToken = tokens.access_token; // See the "Using the access token" section below for information // on how to use the access token to send authenticated requests to // the Realtime Database REST API. }});

Java

Using the Google API Client Library forJava:

// Load the service account key JSON fileFileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");// Authenticate a Google credential with the service accountGoogleCredential googleCred = GoogleCredential.fromStream(serviceAccount);// Add the required scopes to the Google credentialGoogleCredential scoped = googleCred.createScoped( Arrays.asList( "https://www.googleapis.com/auth/firebase.database", "https://www.googleapis.com/auth/userinfo.email" ));// Use the Google credential to generate an access tokenscoped.refreshToken();String token = scoped.getAccessToken();// See the "Using the access token" section below for information// on how to use the access token to send authenticated requests to the// Realtime Database REST API.

Python

Using the google-authlibrary:

from google.oauth2 import service_accountfrom google.auth.transport.requests import AuthorizedSession# Define the required scopesscopes = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/firebase.database"]# Authenticate a credential with the service accountcredentials = service_account.Credentials.from_service_account_file( "path/to/serviceAccountKey.json", scopes=scopes)# Use the credentials object to authenticate a Requests session.authed_session = AuthorizedSession(credentials)response = authed_session.get( "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json")# Or, use the token directly, as described in the "Authenticate with an# access token" section below. (not recommended)request = google.auth.transport.requests.Request()credentials.refresh(request)access_token = credentials.token

Authenticate with an access token

To send authenticated requests to the Realtime Database REST API, pass theGoogle OAuth2 access token generated above as theAuthorization: Bearer <ACCESS_TOKEN> header or theaccess_token=<ACCESS_TOKEN> query string parameter. Here is an example curlrequest to read Ada's name:

curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?access_token=<ACCESS_TOKEN>"

Make sure to replace <DATABASE_NAME> with the name of yourRealtime Database and <ACCESS_TOKEN> with a Google OAuth2 access token.

A successful request will be indicated by a 200 OK HTTP status code. Theresponse contains the data being retrieved:

{"first":"Ada","last":"Lovelace"}

Firebase ID tokens

When a user or device signs in using Firebase Authentication, Firebase creates acorresponding ID token that uniquely identifies them and grants them access toseveral resources, such as Realtime Database and Cloud Storage. You can re-usethat ID token to authenticate the Realtime Database REST API and make requests onbehalf of that user.

Generate an ID token

To retrieve the Firebase ID token from the client, follow the steps inRetrieve ID tokens on clients.

Note that ID tokens expire after a short period of time, and should be usedas quickly as possible after retrieving them.

Authenticate with an ID token

To send authenticated requests to the Realtime Database REST API, pass theID token generated above as the auth=<ID_TOKEN> query string parameter. Hereis an example curl request to read Ada's name:

curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>"

Make sure to replace <DATABASE_NAME> with the name of yourRealtime Database and <ID_TOKEN> with a Firebase ID token.

A successful request will be indicated by a 200 OK HTTP status code. Theresponse contains the data being retrieved:

{"first":"Ada","last":"Lovelace"}

Legacy tokens

If you're still using legacy Firebase authentication tokens, we recommendupdating your REST authentication to one of the authentication methods describedabove.

The Realtime Database REST API still supports authentication via legacyauthentication tokens, including secrets.Your Realtime Database secrets can be found intheService Accountssection of the Firebase console.

Secrets are long-lived credentials. We recommend generating a new secret and revoking the existing one when removing users with secret access (such asowners) from a project.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-09-16 UTC.

Authenticate REST Requests  |  Firebase Realtime Database (2024)
Top Articles
As big banks push for cashless society, neobanks take a different approach
Ask Butler Community
St Thomas Usvi Craigslist
Foxy Roxxie Coomer
Woodward Avenue (M-1) - Automotive Heritage Trail - National Scenic Byway Foundation
Kathleen Hixson Leaked
Part time Jobs in El Paso; Texas that pay $15, $25, $30, $40, $50, $60 an hour online
Mustangps.instructure
Best Cav Commanders Rok
Gt Transfer Equivalency
Items/Tm/Hm cheats for Pokemon FireRed on GBA
Ree Marie Centerfold
Sams Early Hours
Dutch Bros San Angelo Tx
Prosser Dam Fish Count
Yakimacraigslist
Ruse For Crashing Family Reunions Crossword
Glenda Mitchell Law Firm: Law Firm Profile
Georgetown 10 Day Weather
Viha Email Login
Clare Briggs Guzman
8005607994
E32 Ultipro Desktop Version
Restored Republic June 16 2023
Poochies Liquor Store
11526 Lake Ave Cleveland Oh 44102
Bj타리
Feathers
Danielle Moodie-Mills Net Worth
Black Lion Backpack And Glider Voucher
What we lost when Craigslist shut down its personals section
Criglist Miami
Mawal Gameroom Download
Kamzz Llc
Ugly Daughter From Grown Ups
Elanco Rebates.com 2022
Nurtsug
About Us | SEIL
Craigslist Lakeside Az
Kelley Blue Book Recalls
Nba Props Covers
Lonely Wife Dating Club בקורות וחוות דעת משתמשים 2021
Mugshots Journal Star
How I Passed the AZ-900 Microsoft Azure Fundamentals Exam
FedEx Authorized ShipCenter - Edouard Pack And Ship at Cape Coral, FL - 2301 Del Prado Blvd Ste 690 33990
Mauston O'reilly's
Zeeks Pizza Calories
Legs Gifs
Goosetown Communications Guilford Ct
2000 Fortnite Symbols
Skybird_06
Salem witch trials - Hysteria, Accusations, Executions
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 5804

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.