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
How to Remove a User from Office 365 Group using PowerShell?
What does mining difficulty mean?
Riverrun Rv Park Middletown Photos
The Daily News Leader from Staunton, Virginia
30 Insanely Useful Websites You Probably Don't Know About
Lexington Herald-Leader from Lexington, Kentucky
Konkurrenz für Kioske: 7-Eleven will Minisupermärkte in Deutschland etablieren
Acts 16 Nkjv
Nordstrom Rack Glendale Photos
7543460065
CA Kapil 🇦🇪 Talreja Dubai on LinkedIn: #businessethics #audit #pwc #evergrande #talrejaandtalreja #businesssetup…
Chase Claypool Pfr
Mndot Road Closures
Myql Loan Login
Kvta Ventura News
National Weather Service Denver Co Forecast
Destiny 2 Salvage Activity (How to Complete, Rewards & Mission)
Elemental Showtimes Near Cinemark Flint West 14
How do I get into solitude sewers Restoring Order? - Gamers Wiki
Vipleaguenba
Libinick
Kamzz Llc
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Allentown Craigslist Heavy Equipment
Morristown Daily Record Obituary
Craigslist Personals Jonesboro
How many days until 12 December - Calendarr
Conscious Cloud Dispensary Photos
Yonkers Results For Tonight
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Craig Woolard Net Worth
Gilchrist Verband - Lumedis - Ihre Schulterspezialisten
Student Portal Stvt
Evil Dead Rise Showtimes Near Sierra Vista Cinemas 16
Unreasonable Zen Riddle Crossword
Kleinerer: in Sinntal | markt.de
Craigslist Middletown Ohio
Boondock Eddie's Menu
Appleton Post Crescent Today's Obituaries
Mixer grinder buying guide: Everything you need to know before choosing between a traditional and bullet mixer grinder
Xxn Abbreviation List 2023
Gopher Hockey Forum
Arigreyfr
Mychart Mercy Health Paducah
Pink Runtz Strain, The Ultimate Guide
Cleveland Save 25% - Lighthouse Immersive Studios | Buy Tickets
Jimmy John's Near Me Open
Devotion Showtimes Near Showplace Icon At Valley Fair
Lesson 5 Homework 4.5 Answer Key
Jesus Calling Oct 6
Factorio Green Circuit Setup
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.