Authenticating with Mobile Services

Let’s be honest, most people use Facebook or at least have an account, and if they dont have that chances are they have Twitter, Microsoft, or a Google account, if not more than one.  So why would you ever invest in your own authentication system? Usually the answer is something along the lines of “OAuth is hard”.  While that is true, we can turn to services like Azure Mobile Services and Parse which can take care of that aspect for us.

Understanding the Authentication Model

Generally, with third party authentication systems like Facebook, Twitter, Google, and Microsoft OAuth is used.  In OAuth, the application is given a set of unique values (the key and the secret).  Using these values the application will transmit a request for authentication to the third party. The user literally leaves your site, in most cases, and goes to Facebook or whatever.  Here they enter their credentials and grant the appropriate permissions to the app.  Once complete a callback is used which allows the application to recent the access token.  This is the token that will be passed as the application makes the desired API calls.  It identifies the application and the user to the service.  At no point does the application ever have to store the credentials used to access the service.

Unfortunately, making all of this work is difficult, those simpler with newer frameworks and approaches.  The difficulty has not slowed the adoption of this model for mobile applications and so this is why providers like Azure and Parse have worked to abstract the complexities away for developers.

The Setup

As with Push Notifications, Mobile Services allows you to store the values needed for operations to be carried out.  From the main page for your Mobile Service select Identity.

image

This page will contain four sections, one for each supported authentication mechanism, below are the links to get the values you will need)

Once you get the appropriate values added to the correct fields under the Identity section, hit Save.

One word of caution: I noticed during my testing that authentication didn’t seemed to work well right away with Facebook and Microsoft especially.  If you start to notice this, you might have to take some time and wait for things to propagate, especially if you start by creating a new app.

Tip: All of the callback URLs should point to your Azure Mobile Service Url (only Google uses a slight variation on this).

Coding

I wont lie, Microsoft has really done an awesome job of making this super easy for developers, almost too easy.  Here is the basic code for performing authentication:

   1:              try
   2:              {
   3:                  var client = new MobileServiceClient("MOBILE SERVICE URL", "APP KEY");
   4:                  var user = await client.LoginAsync(MobileServiceAuthenticationProvider.Facebook);
   5:   
   6:                  return user.UserId;
   7:              }
   8:              catch (InvalidOperationException)
   9:              {
  10:                  return string.Empty;
  11:              }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

What is happening here is a new MobileServiceClient is being created and then we are logging in.  What is important to understand here is that this is NOT hitting the Azure Mobile Service endpoints.  This is only about getting the UserId for the user based on the particular service; in other words this does not map to one of the triggers talked about earlier.  Instead, it is storing the user information inside the client reference.  This way when a request is made to one of the 4 operations, user information is available.

As you can see in this case I am specifying Facebook authentication, but by simply changing Facebook to MicrosoftAccount, Google or Twitter, I can change my authentication mechanism.

As you might expect, the first time this code is raised within the application you will be redirected, however, on subsequent calls the code passes through after checking with Mobile Services.  A good idea here may be to wrap the MobileServiceClient so that the two calls can be combined. I can see this working well especially as you can take advantage of the awaitable method concept in .NET.

Permissions

One of the great advantages to using the authentication concept in this way is you can then require users to be logged in before accessing your endpoints.  From the Mobile Service Home Screen, select Data –> –> Permissions.  This will give you a drop down for each operation with 4 operations:

image

  • Anybody with the Application Key
    • Generally this is going to be very similar to Everyone.  Never consider your Application Key a secret, it isn’t.  It is generally used to provide everyone-type access via the client interfaces, though not required.  My recommendation is to use this permission setting on tables/endpoints you only want selective users to know about, but the security of which are not overly critical to the application
  • Everyone
    • Everyone can hit this table/endpoint.  Think of this as defining a public table which may be a part of a wider public API
  • Only Authenticated Users
    • This requires the user be authenticated (what we showed above) before the endpoint will be able to process the request.  This is the ideal permission for most applications that have users or varying levels of access.
  • Only Scripts and Admins
    • Similar to the Application Key, this key (the Master Key) is designed to be secret and should be closely guarded.  Useful for Admin level roles and automated (trusted) scripts

Remember that all a “table” is in Mobile Services is an endpoint, a resource if you will.  Making requests against that resource will invoke the standard triggers.  Here is an example of the simplest insert trigger allowed:

function insert(item, user, request) {
    request.execute();
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Notice the parameters to this method.  item is the actual item being sent to the request, request is information about the incoming request, such as query string parameters.  In the case of an authenticated user, user will contain information about the user, notably the User Id, which can be stored to relate information back to a given user.  This is something I will expand on in a future post.

Needless to say, the user information is not passed and the table/resource requires the user to be authenticated the request will fail.

Closing

Let’s be quite honest. I do not see a legitimate reason for most applications to employ their own login system.  We are already seeing these shared login systems appear quite literally everywhere, and why not?  Most people have at least one of the 4 account types mentioned above and using this means one less username/password authentication a user has to remember and keep track of.  To be honest, there isn’t a need to even store the information coming from Facebook for simple authentication, Mobile Services can handle that, however, if you desire to get information from Facebook you will need to take additional steps.  I intend to cover that in other posts.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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