Skip to content

Instantly share code, notes, and snippets.

@kenjij
Last active Nov 9, 2021
Embed
What would you like to do?
Firebase REST authentication

Google OAuth for Service Accounts/Firebase REST How-to

Firebase REST queries require access_token parameter for full access. This is Google’s OAuth 2.0 for service accounts.

Get credentials of the service account

  • Firebase Console > Settings > Project settings > Service accounts tab
  • Click Generate new private key and download credentials
    – OR –
    Click Manage all service accounts and create a new service account, then download the credentials

Prepare JWT to request token

require 'jwt'
now_seconds = Time.now.to_i
payload = {
  iss: EMAILADDRESS,
  scope: 'https://www.googleapis.com/auth/firebase.database https://www.googleapis.com/auth/userinfo.email',
  aud: "https://www.googleapis.com/oauth2/v4/token",
  iat: now_seconds,
  exp: now_seconds + 60
}
pkey = OpenSSL::PKey::RSA.new PRIVATEKEY
JWT.encode payload, pkey, "RS256"
  • EMAILADDRESS = of the service account. Obtain from the credentials file above.
  • PRIVATEKEY = RSA key, also from the credentials file above.
  • The exp should be max 60s as a general security practice; this is the lifetime of this JWT, not Google's access token.

Make the access token request

POST request to: https://www.googleapis.com/oauth2/v4/token
With parameters: grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer & assertion=

curl --data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer' -d 'assertion=<JWT>' https://www.googleapis.com/oauth2/v4/token

Obtain the key from the JSON response. Google's access token always has the lifetime of 1 hour.

{
 "access_token": "ya29.ElsrBD0lh…...",
 "token_type": "Bearer",
 "expires_in": 3600
}

Use the access token

Add “.json” at the end of the URL to make it a REST call. Add the access token as a parameter,

curl -i 'https://<PROJECTID>.firebaseio.com/path/name.json?access_token=<ACCESSTOKEN>'

or add header Authorization: Bearer <ACCESSTOKEN>.

@bolandrm
Copy link

bolandrm commented Jun 6, 2020

Huge help, thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment