How I Pulled It All Together-Xamarin Forms, Azure, ASP.NET MVC 5 and Azure Mobile Services
So this won't be a lenghty post giving you step by step instructions but instead I'll point you to all the resources that helped me over a 2 week period to go from "I should be able to do it" to reality.
In building a cross platform app for a client using Xamarin.Forms I decided to give Azure and Azure Mobile Services a try after being convinced it was the route to go after meeting some great people with Microsoft at Xamarin Evolve 2014. The client also needed a companion website to administer users and other administrative tasks. Even though I've been using .Net since inception, I never got into their MVC platform. MVC wasn't new to me since I'd used it with other platforms.
So, here was the task..create a MVC website with a Azure SQL Database and an Xamarin app using the same Azure Database while making use of Azure Mobile Services for ease of authentication and api access.
First Step: Create ASP.NET MVC website and publish to Azure
Follow this tutorial to the letter. It introduced me to Entity Framework and guides you through every step until you have your site running on Azure.
http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-1
Second Step: Setting Identity 2.0 For Authentication Using
Here I'm able to take the database and site that we created above and add Identity Framework for user authentication
http://danieleagle.com/blog/2014/05/setting-up-asp-net-identity-framework-2-0-with-database-first-vs2013-update-2-spa-template/
Third Step: Add Log In, Email Confirmation and Password Reset to
For some strange reason, none of the ASP.NET MVC templates give you user administration out of the box(creating/editing/deleting users and roles) nor other features such as email confirmation and password reset. Here's two guides to help you out.
http://typecastexception.com/post/2014/06/22/ASPNET-Identity-20-Customizing-Users-and-Roles.aspx#Extending-Identity-Role
http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset
Fourth Step: Create our Azure Mobile Service
Follow the easy steps in the Azure Control panel to create the mobile service. Make sure you select .Net as your backend and select your Azure SQL database created earlier. One lesson learned..contrary to what a lot of tutorials say, you do not need to move your SQL tables from your dbo schema to the schema name of Azure Mobile Service when implementing a .NET backed.(this IS required however with a Javascript backed). The following two guides will have you connecting your mobile service to the existing Azure SQL database in no time.
http://blogs.msdn.com/b/azuremobile/archive/2014/05/27/bring-your-own-database-with-the-net-backend.aspx
http://blogs.msdn.com/b/azuremobile/archive/2014/05/22/tables-with-integer-keys-and-the-net-backend.aspx
Fifth Step: Configure Azure Mobile Service For Identity Authentication
Out of the box, Azure Mobile Service lets you easily use providers such as Facebook, Twitter and Active Directory for authentication. But since we are using Identity in the MVC site, it would be great to authenticate our mobile users using the same credentials. Here's how to do that.
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-get-started-custom-authentication/
I did modify the CustomLoginController from the above guide to a simpler implementation. Here I'm simply using the PasswordHasher to compare the password provided with the hashed password retrieved for the account with the provided username/email.
public HttpResponseMessage Post(LoginRequest loginRequest) { ExistingCommunityHealthDatabaseContext context = new ExistingCommunityHealthDatabaseContext(); AspNetUser aspnetUser = context.AspNetUsers.Where(a => a.UserName == loginRequest.username).SingleOrDefault(); if (aspnetUser != null) { PasswordHasher hasher = new PasswordHasher(); if (hasher.VerifyHashedPassword(aspnetUser.PasswordHash, loginRequest.password) != PasswordVerificationResult.Failed) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginRequest.username)); LoginResult loginResult = new CustomLoginProvider(handler).CreateLoginResult(claimsIdentity, Services.Settings.MasterKey); return this.Request.CreateResponse(HttpStatusCode.OK, loginResult); } } return this.Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid username or password"); }
Last Step: Authenticate user in my Xamarin.Forms app and post a new item
Follow the easy steps to add the mobile services package to your Xamarin project. Once that's done just follow this flow. Send a JSON request to our CustomLoginController we created in Step 5, retrieve the authentication token and store it to be passed in future api calls such as posting an item.
public static MobileServiceClient MobileService = new MobileServiceClient( "https://yourAzureMobileService/", "applicationkey" );
-RestSharp to send credentials and retrieve/save token
var client = new RestClient(); var request = new RestRequest("https://yourAzureMobileService/Api/CustomLogin", Method.POST); request.AddParameter("username", "[email protected]"); // adds to POST or URL querystring based on Method request.AddParameter("password", "foo"); // adds to POST or URL querystring based on Method request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; IRestResponse response = client.Execute(request); MobileService.CurrentUser = new MobileServiceUser(response.Data.user.userId); MobileService.CurrentUser.MobileServiceAuthenticationToken =response.Data.authenticationToken;
-Set a reference to a table manager that we can call from within our Forms shared code
testTable = MobileService.GetTable(); TestItemManager = new testItemManager(testTable); App.SetTestItemManager (TestItemManager);
The Xamarin TodoAzure sample will give you more insight on getting all those pieces in place. https://github.com/conceptdev/xamarin-forms-samples/tree/master/TodoAzure
-Post a new item from our shared code
await App.TestManager.SaveTaskAsync (new testDto { name = "Awesome item2"});
That's it! We've come full cycle now. An ASP.NET MVC website with Identiy Authentication hosted on Azure with an Azure SQL Database and a companion Xamarin.Forms app using Azure Mobile Services.
Like I said, its not a complete step-by-step tutorial but its definitely enough to have you on your way.