Part 4: Azure Mobile Services: What you need to know about Authentication and Authorization


This tutorial series takes you through how Azure Mobile Services provides Mobile-Backend-As-A-Service by discussing various features and basics of how to get started.

Part 1: How Azure Mobile Services enable your Cloud First Mobile First World
Part 2: Azure Mobile Services: What you need to know to get started with Storage Services
Part 3: Azure Mobile Services: What you need to know to get started with Notification Hub

 

image

Authentication and Authorization is a key component of any app. One of the most powerful capabilities of Azure Mobile Services is how easy it is to add user authentication to mobile apps. Again, the value proposition comes from a cross platform support, also the authentication can be done using several third party identity service providers such as Facebook, Google, Microsoft, Twitter and Azure Active Directories. The basic idea is to register your app with one of the various identity service provider’s developer site which provides you with the key id and a secret. This information is fed into the mobile services portal and then the app can use the services of the identification provider to authenticate.

The flow of the authentication procedure is shown in the diagram below. Authentication uses OAuth behind the scenes which is otherwise quite a complex procedure and Mobile Services does a great job at abstracting all the details. Mobile Service is registered with identity provider to provide authentication. The client calls the auth method and passes in the provider name. Mobile services and the provider does OAuth to authenticate the users. The UserId and token are returned to the client and is stored and is accessible from the Mobile services.

image

 

In order to authenticate and authorize users, there are few basic steps:

  1. Register App for authentication and configure Mobile Services
  2. Restrict Permissions to authenticate users
  3. Add Authentication to app
  4. Use scripts to authorize users in Mobile Services

Step 1:

Registration of the app can be done in two steps. First, one needs to go and register the app name at the identity provider’s developer site. Once the registration is done, the package id and the client secret yielded is entered in the portal. For example, if you want to authenticate a Live Id, you would be registering your app in the Windows Dev Centre and getting the client id and secret from the App Settings:

image

This package id, client id and secret needs to be entered in the Azure Mobile Services Portal as shown below under the identity tab.

image

 Step 2:

Once the registration part is done, one needs to restrict the permissions on the users. Under the data tab in the portal, we need to go to the table and click on permissions. In the permissions tab, we need to change the option to “only authenticated users” for each of the four operations of insert, update, delete and read.

imageNow if you try to run your app, you will get an unauthorized access as only authenticated users will be allowed to access the data:

image

Step 3:

Now let us add the piece which will authenticate the user and give access to the data. Let us look into the sample code that needs to be added to your app. Essentially, we have to connect to the identity provider, enter user credentials. An object for the user id needs to be initialized and a method needs to be added which will call the identy provider. If using a Windows Universal App, the following code snippet does the trick:

 1: private MobileServiceUser user;
 2:  
 3:         
 4:         private async System.Threading.Tasks.Task AuthenticateAsync()
 5:         {
 6:             while (user == null)
 7:             {
 8:                 string message;
 9:                 try
 10:                 {
 11:                     user = await App.MobileService
 12:                         .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
 13:                     message =
 14:                         string.Format("You are now logged in - {0}", user.UserId);
 15:                 }
 16:                 catch (InvalidOperationException)
 17:                 {
 18:                     message = "You must log in. Login Required";
 19:                 }
 20:  
 21:                 var dialog = new MessageDialog(message);
 22:                 dialog.Commands.Add(new UICommand("OK"));
 23:                 await dialog.ShowAsync();
 24:             }
 25:         }

 

The value of MobileServiceAuthenticationProvider can be changed to the Identity service provider that you want to use for authentication. Once this is added, the method needs to be called from the onNavigated method:

 1: protected override async void OnNavigatedTo(NavigationEventArgs e)
 2:         {
 3:             await AuthenticateAsync();
 4:             RefreshTodoItems();
 5:         }

 

That's it, now you only allow authenticated users to access your data.

Step 4:

Now that authentication is taken care of, let us see how do we authorize users to access their own data using server scripts. We need to register scripts in the portal itself and is done against each of the operations of insert, delete, read and update. We need to go to the portal, select the table and then click on script which will take you to the script options.

image

Replace the insert script with the following to add a userID column:

 1: function insert(item, user, request) {
 2:  
 3:     
 4:     item.userid = user.userID;
 5:     request.execute();
 6:  
 7: }

The Read operation can be replaced as follows:

 1: function read(query, user, request) {
 2:     query.where({userID: user.userID});
 3:     request.execute();
 4:  
 5: }

 That sets up insert and read operation for authorized users.

 

Summary

In this section, we see how easy it is to integrate authentication and authorization to your app. We discussed the concept which primarily uses OAuth in the backend, abstracting the details from us. We also saw the various third party identity service providers using which we authenticate the users. There are few other forms of authentication such as Single Sign-on and Multi factor authentication which can be looked into as per your interest. Please reach out to me @AdarshaDatta and share your stories with me about Azure Mobile Services.

Comments (1)

  1. ShyamalPandya says:

    Really nice article. Exactly the one I was looking for. Will try Single Sign-On by myself for sure. Thanks.

Skip to main content