Firebase REST queries require access_token
parameter for full access. This is Google’s OAuth 2.0 for service accounts.
- https://firebase.google.com/docs/reference/rest/database/user-auth
- https://developers.google.com/identity/protocols/OAuth2ServiceAccount
- 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
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.
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
}
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>
.
Huge help, thanks for sharing!