Saturday, 1 March 2014

C# example of using Firebase REST API

Once I got my head around how Firebase worked (see here multiple Firebase related posts), my next step was to figure out a way to send data to it from C#, namely from TeamMentor.

To try it out, I used the Web C# REPL that is part of TeamMentor's admin section (which gives me a great interactive environment to quickly test new APIs).

1) Retrieving data (with no Authentication)

The first test was to send the following simple GET request to Firebase's REST API:

Since (at this stage) there was no security enabled on the Firebase app, that simple GET request returned the entire dataset (if I had send the request to /aaa/.json, I would receive the objects from the aaa child object)

2) Sending data (with NO authentication)

Next I tried to submit POST data (which simulates Firebase's Javascript API push behaviour), and it took me a couple tries to get the format right:

The request above worked, but only because I used " instead of ' (for the json data), and there was at least one name-value pair.

The response received contained the unique key that was assigned to the data submitted (this key is time specific, so it will change on every request, in a way that sorting them, will result in the submitted order)

Here (below) is the admin panel for the tm-admin-test Firebase app used (note that the data submitted was added as child nodes of the key value received (shown above))

Note that at the moment the Firebase Security Rules look like this (i.e. anonymous users have read and write privileges to all hosted data)

3) Sending data (WITH authentication)

To make this more realistic, lets use this test chat application which uses Authentication to communicate with the Firebase app:

Let's say that we wanted the data to by read by everybody but only be written by an authenticated user (in this case me).

Here are the Firebase Security Rules required to enforce those security requirements:

(see the Trying out Firebase (Beta) hosting solution and good example of Firebase Security rules post for a more detailed, complex and powerful Firebase Security policy)

Since at this stage I was not sure how to use the REST API to login as a particular user (with a email + password combination), I used the auth key that can be created (and revoked) from the Firebase admin panel:

This key can then be appended to the GET or POST requests as the auth querystring parameter:

... and as the image below shows, we are still able to submit data (now being authenticated in Firebase). Note that without the auth parameter, we would get a 403 error

And since I still had the client chat app opened in Eclipse, I was able to see in real-time the data submitted (in this case, the last chat item: AAAAAA:Now with AuthToken )

Post a Comment