Trying out Azure Mobile Services to create a rest api and a Facebook authenticated web app

I heard about Azure Mobile Services on Yet Another Podcast #86 where Jesse Liberty interviews Josh Twist. There was a few things to the service that made me very interested:

Azure Mobile Services

  • Inside the Azure portal
  • Easy to setup a robust Restful API over an accompanying Azure SQL database
    • With permissions per user, extensible with the help of server side js scripts (on CRUD operations)
    • Using authentication from Facebook, Twitter, Google or Microsoft Live
    • The JSONs are stored in tables, with properties automapped to columns, and schema automatically created
  • Scheduled tasks (as js scripts)
  • Addons like Pusher
  • Easy to customize mentioned scripts (just js that runs in a nodejs app)

So I think Azure Mobile Services is a very promising service for greatly simplifying creation of the server side of a web application. Why should I need to create my own custom C# (or whatever) server code for a restful api over data, same stuff as has been done gazillions of times already on the web? Azure Mobile Services provides a portal where I can setup all I need, and overview, manage and edit it.

I wanted to try it out and put the pieces together to make a proof of concept HTML5 application that uses Facebook authentication and allows a per user CRUD of text items into my mobile service database. Plus it has some push functionality just for fun…

Azure Mobile Services (a.k.a. “Zumo”, I’ll just use that shorter name further on) has a nice site and many high quality help pages with step by step tutorials. It is in preview mode currently. Zumo is primarily targeted for mobile devices (and Windows 8 store apps) and has several examples and pre made help libraries for those. It even creates sample apps with credentials on the fly for you if you like. I used a few of those to learn some about the communication bits. Hopefully they’ll make the Rest bits just as easy eventually.

I needed the following pieces for my experiment:

  • The Zumo service itself. Free to try out, in preview mode.
    • A data table in Zumo. Just with a name and with permissions set for all operations first to “Everyone” and later changed to “only Authenticated users”
    • Server side scripts on that table
      • insert: add userid to the stored items
      • read: only query for the items that has userid of the current user
  • A web site that serves the files, and talks to the Zumo service (Zumo does not allow cross origin requests). One of the developers in the Azure team, Tom Rudick,  has made a small 43 locs “zumo-proxy” in node which is does just that. Just fill in the Zumo identifications and url and get going. (Do not add protocol name to the forward url, i.e. “myzumo.azure-mobile.net”)
    • I opened my copy of zumo proxy in WebMatrix, created an empty web site within Azure and used its publish settings
  • A Facebook app
  • Some client side code
    • connect to the Facebook app and get a facebook token
      • using the Facebook js scripts, it asks automatically user to allow the application
    • connect to the Zumo via the proxy to get a zumo token
    • add and get the items (with security token in the ajax header)

The things that took most time was go get the auth working, and to get the ajax requests right. After I learned to actually read the error messages :-p and add some logging to my node application, And – important help from Tom Rudick, I got the whole thing rolling late night.

I started out with allowing data operations for everyone so I could get going without the authentication bits:

// the zumo-proxy resends any request to /zumo/* straight to the zumo service url
// get items
$.ajax("/zumo/tables/todoitem", function (data) {
 console.log(data);
});

// post a new todoitem
$.ajax({
 url: "/zumo/tables/todoitem",
 contentType: "application/json",
 type: "post",
 data: JSON.stringify({text:"bar",complete:false})
});

Then I added Facebook client side library, and login parts:

<script src="https://connect.facebook.net/en_US/all.js" type="text/javascript"></script>

 

</span>
<pre>function initFacebook() {
    FB.init({
        appId: '{{my facebook app id}}',
        cookie: true,
        xfbml: true,
        status: true
    });
    loginFacebook();
}
function loginFacebook() {

    FB.getLoginStatus(function (response) {
        if (response.authResponse) {
            facebookHandleAuthResponse(response.authResponse);
        } else {
            FB.login(function (response) {
                if (response.authResponse) {
                    facebookHandleAuthResponse(response.authResponse);
                }
            });
        }
    });

}

function facebookHandleAuthResponse(authResponse) {

    // get auth token from Zumo with the help of the auth'd facebook token
    // set the header x-zumo-auth with $.ajaxSetup (for all coming ajax requests)

    $.ajax({
        url: "/zumo/login/facebook",
        type: "post",
        data: JSON.stringify({ "access_token": authResponse.accessToken }),
        contentType: "application/json",
        success: function (response) {
            $.ajaxSetup({ headers: { "x-zumo-auth": response.authenticationToken} });
        }
    });

}

When I first ran my application from Facebook, (apps.facebook.com/mycoolapp) I got a 405 error. Turns out Facebook does not handle a static file (index.html) as a start page, it does some test to post to the start page, and a static page does not allow posts. Simple workaround : rename index.html to default.aspx. And make default.aspx the start page in the Azure web site.

The scripts that runs in Zumo on every insert/read operation

For inserts: add userid to the item object:

function insert(item, user, request) {

    item.userId = user.userId;
    request.execute();

}

The first insert will create the necessary columns in the database table.

For reads: only get the items with userId == id of current user:

function read(query, user, request) {

    query.where({ userId: user.userId });
    request.execute();

}

Push notifications

I also added a Pusher service. It can be done as an addon, but it’s not available currently from my part of the world (only for US?). So I signed up for a accound directly on the Pusher site. Very easy to do. And added the 50 locs “Pusher” nodejs server side module directly within a Scheduled script (like a cron-job that executes js), and got it working.

References

Building HTML5 Apps with Windows Azure Mobile Services by Tom Ruddick

Using Azure Mobile Services in your web apps through ASP.NET Web API by Filip Woj

Pusher node server

Zumo Proxy

Advertisements

3 thoughts on “Trying out Azure Mobile Services to create a rest api and a Facebook authenticated web app

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s