2
votes

I am trying to authenticate with ruby to firebase as Service Account. So what I did so far, is using Google auth lib as I always did (in other google services):

require 'googleauth'
scopes =  ["https://www.googleapis.com/auth/firebase.database"]
tt = Google::Auth.get_application_default(scopes).fetch_access_token

I get the tt["access_token"] and then I do something like

curl -X POST -d '{"user_id" : "jack", "text" : "Ahoy!"}' 'https://project-xxxxxxxxxxxxxxxxxxx.firebaseio.com/message_list.json?access_token=ya29.CjHzAsjcGEQsSppI9AKCV9g4Uen7qlREI3N_nCGDsWkLh6ZSCg5JmNYzIU8NuV6PAq7h'

Like they say in https://firebase.google.com/docs/reference/rest/database/user-auth#section-get

and I get: Permission denied (that is because in our DB Rules we said auth != null. So I went ahead and called ?auth=ya29.CjHzAsjcGEQsSppI9AKCV9g4Uen7qlREI3N_nCGDsWkLh6ZSCg5JmNYzIU8NuV6PAq7h

And I got:

"{\n  \"error\" : \"Could not parse auth token.\"\n}\n"

How am I supposed to authenticate to Firebase WITHOUT nodejs... just a simple REST???

Please assist!

Thanks!

1
The access token you get back from Google is not a valid token for Firebase. To exchange it, you will indeed require a trusted process (e.g. a server) to mint a JWT. Also see stackoverflow.com/questions/35247677/…Frank van Puffelen
@FrankvanPuffelen did that, and it said kid header is not in the token... – Himberjack 13 mins agoHimberjack

1 Answers

3
votes

Here's a fully baked example, assuming you have an access token as described above:

require 'cgi'
require 'json'
require 'net/https'
require 'uri'

ACCESS_TOKEN = 'XXX'
DATABASE_NAME = 'YYY'

path = '/example'
auth_variable = {uid: 'ruby-admin'}
payload = {my: 'data'}

uri = URI("https://#{DATABASE_NAME}.firebaseio.com#{path}.json?auth_variable_override=#{CGI::escape auth_variable.to_json}")
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')

req.body = payload.to_json
req['Authorization'] = "Bearer #{ACCESS_TOKEN}"

http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true

res = http.request(req)

puts res.body

You can edit auth_variable to change the auth variable available in security rules, and payload is obviously your data you want to post.