After seeing a couple of posts in this topic, I decided to try to get this scenario working – and having never used the OAuth support in MVC, it was a good opportunity for me to learn a little about it. So here’s a very detailed, step-by-step of what I did (and worked for me), hopefully it will be useful if you got to this post. As in my previous step-by-step post, it can have more details than some people care about, so if you’re only interested in the connection between the MVC application and Azure Mobile Services, feel free to skip to the section 3 (using the Azure Mobile Service from the MVC app). The project will be a simple contact list, which I used in other posts in the past.
Let’s start with a new MVC 4 project on Visual Studio (I’m using VS 2012):
And select “Internet Application” in the project type:
Now the app is created and can be run. Now let’s create the model for our class, by adding a new class to the project:
And after building the project, we can create a new controller (called ContactController), and I’ll choose the MVC Controller with actions and views using EF, since it gives me for free the nice scaffolding views, as shown below. In the data context class, choose “<New data context...>” – and choose any name, since it won’t be used once we start talking to the Azure Mobile Services for the data.
Now that the template created the views for us, we can update the layout to start using the new controller / views. Open the _Layout.cshtml file under Views / Shared, and add a new action link to the new controller so we can access it (I’m not going to touch the rest of the page to keep this post short).
At this point the project should be “F5-able” – try and run it. If everything is ok, you should see the new item in the top menu (circled below), and after clicking it you should be able to enter data (currently being stored in the local DB).
Now since I want to let each user have their own contact list, I’ll enable authentication in the MVC application. I found the Using OAuth Providers with MVC 4 tutorial to be quite good, and I was able to add Facebook login to my app in just a few minutes. First, you have to register a new Facebook Application with the Facebook Developers Portal (and the “how to: register for Facebook authentication” guide on the Windows Azure documentation shows step-by-step what needs to be done). Once you have a client id and secret for your FB app, open the AuthConfig.cs file under the App_Start folder, and uncomment the call to RegisterFacebookClient:
At this point we can now change our controller class to require authorization (via the [Authorize] attribute) so that it will redirect us to the login page if we try to access the contact list without logging in first.
Now if we either click the Log in button, or if we try to access the contact list while logged out, we’ll be presented with the Login page.
Notice the two choices for logging in. In this post I’ll talk about the Facebook login only (so we can ignore the local account option), but this could also work with Azure Mobile Services, as shown in this post by Josh Twist.
And the application now works with the data stored in the local database. Next step: consume the data via Azure Mobile Services.
Let’s start with a brand new mobile service for this example, by going to the Azure Management Portal and selecting to create a new Mobile Service:
Once the service is created, select the “Data” tab as shown below:
And create a new table. Since we only want authenticated users to access the data, we should set the permissions for the table operations accordingly.
Now, as I talked about in the “storing per-user data” post, we should modify the table scripts to make sure that no malicious client tries to access data from other users. So we need to update the insert script:
And finally delete:
We’ll also need to go to the “Identity” tab in the portal to add the same Facebook credentials which we added to the MVC application (that’s how the Azure Mobile Services runtime will validate with Facebook the login call)
The mobile service is now ready to be used, we need now to start calling it from the web app.
In a great post about this topic a while back, Filip W talked about using the REST API to talk to the service. While that is still a valid option, the version 1.0 of the Mobile Service SDK NuGet package also supports the “full” .NET Framework 4.5 (not only Windows Store or Windows Phone apps, as it did in the past). So we can use it to make our code simpler. First, right-click on the project references, and select “Mange NuGet Packages…”
And on the Online tab, search for “mobileservices”, and install the “Windows Azure Mobile Services” package.
We can now start updating the contacts controller to use that instead of the local DB. First, remove the declaration of the ContactContext property, and replace it with a mobile service client one. Notice that since we’ll use authentication, we don’t need to pass the application key.
Now to the controller actions. For all operations, we need to ensure that the client is logged in. And to log in, we need the Facebook access token. As suggested in the Using OAuth Providers with MVC 4 tutorial, I updated the ExternalLoginCallback method to store the facebook token in the session object.
Now we can use that token to log in the web application to the Azure Mobile Services backend. Since we need to ensure that all operations are executed within a logged in user, the ideal component would be an action (or authentication) filter. To make this example simpler, I’ll just write a helper method which will be called by all action methods. In the method, shown below, we take the token from the session object, package it in the format expected by the service (an object with a member called “access_token” with the value of the actual token), and make a call to the LoginAsync method. If the call succeeded, then the user is logged in. If the MobileService object had already been logged in, its ‘CurrentUser’ property would not be null, so we bypass the call and return a completed task.
Now for the actions themselves. When listing all contacts, we first ensure that the client is logged in, then retrieve all items from the mobile service. This is a very simple and naïve implementation – it doesn’t do any paging, so it will only work for small contact lists – but it illustrates the point of this post. Also, if the login fails the code simply redirects to the home page; in a more realistic scenario it would send some better error message to the user.
Displaying the details for a specific contact is similar – retrieve the contacts from the service based on the id, then display it.
Likewise, creating a new contact involves getting the table and inserting the item using the InsertAsync method.
And, for completeness sake, the other operations (edit / delete)
That should be it. If you run the code now, try logging in to your Facebook account, inserting a few items then going to the portal to browse the data – it should be there. Deleting / editing / querying the data should also work.
Logging in via an access (or authorization) token currently only works for Facebook, Microsoft and Google accounts; Twitter isn’t supported yet. So the example below could work (although I haven’t tried) just as well for the other two supported account types.
The code for this post can be found in the MSDN Code Samples at http://code.msdn.microsoft.com/Flowing-authentication-08b8948e.