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
VPN Gateway: Everything You Need To Know
Valuation Reports - The Different Types and When you May Need Them - Rees Richards & Partners
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
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.