Skip to content

Instantly share code, notes, and snippets.

@andrewsheelan
Created February 14, 2018 20:18
Show Gist options
  • Save andrewsheelan/3b86f17feff87c7a1f121d2bb561e0bd to your computer and use it in GitHub Desktop.
Save andrewsheelan/3b86f17feff87c7a1f121d2bb561e0bd to your computer and use it in GitHub Desktop.
Ruby Token generator for Firebase Admin SDK
################################################################################################################
# Requires Firebase Database account and a JSON file. This can be placed in config/initalizers if using Rails
# Download it from the account > service area and renamed it as privatekey.json
# Also requires ruby-jwt gem.
# Usage: Firebase.generate_token(uid)
#
# Rule in Firebase to authorize based on user_id for this token (o_payload passes user_id):
# Path: https://#{project_id}.firebaseio.com/users/#{uid}
# {
# "rules": {
# "users":{
# "$user_id": {
# ".read": "auth.user_id == $user_id",
# ".write": "auth.user_id == $user_id"
# }
# }
# }
# }
################################################################################################################
require 'jwt'
class Firebase
IDENTITY_TOOLKIT = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit'.freeze
SCOPE = 'https://www.googleapis.com/auth/identitytoolkit'.freeze
def self.generate_token(uid)
kid = service_account[:private_key_id]
s_pkcs8_pem = service_account[:private_key]
sub = service_account[:client_email]
t_now = DateTime.now.to_i
t_end = 1.hour.from_now.to_i
o_payload = {
aud: IDENTITY_TOOLKIT, scope: SCOPE,
exp: t_end, iat: t_now, iss: sub, sub: sub, user_id: uid
}
private_key = OpenSSL::PKey::RSA.new(s_pkcs8_pem)
{
user_id: uid,
token: JWT.encode(o_payload, private_key, 'RS256'),
user_path: "https://#{service_account[:project_id]}.firebaseio.com/users/#{uid}",
expires_at: t_end
}
end
def self.service_account
@service_account ||= JSON.parse(
File.open('privatekey.json', 'rb').read
).symbolize_keys
end
end
class << Firebase; private(:service_account); end
@andrewsheelan
Copy link
Author

The above token expires every hour.

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