问题
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:
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.
来源:https://stackoverflow.com/questions/37539066/how-to-authenticate-in-ruby-via-rest-api