Share via


November 2014

Volume 29 Number 11


Azure Insider : Security and Identity Management with Azure Mobile Services

Bruno Terkaly | November 2014

Bruno Terkaly Satya Nadella has clearly defined the new Microsoft vision statement. He has stated we live in a world that is “Mobile-­First/Cloud-First.” This is no surprise. Microsoft has been pursuing mobile and cloud technologies for several years now. The industry is changing and the pressure for IT leaders to embrace the bring-your-own-device (BYOD) revolution has never been greater.

Supporting the brave new world of BYOD in the enterprise is a top priority. In this article, we’ll help you understand how the cloud can help line-of-business (LOB) application developers create and support Apple iOS, Google Android, and Windows Phone apps. We’ll address the device-management challenges facing corporations of all sizes. We’ll also cover some of the low-level native Objective-C code you’ll need in order to properly manage OAuth 2.0 tokens from Azure Mobile Services. The key capability is saving a token securely on a mobile device so users aren’t forced to log in every time they want to use an application.

Key Characteristics of LOB Apps

There are many issues to consider when creating LOB apps. One of the most important is identity management (see Figure 1). We’re not just talking about user identity, but also device identity. Those two factors combined is often called compound identity. This makes sense because LOB apps typically have access to confidential corporate resources.

Overview of iOS Line-of-Business Applications
Figure 1 Overview of iOS Line-of-Business Applications

Device Management

One thing is clear about centralized IT: It needs to enforce some type of control over personal devices. In an ideal world, IT can force users to fully domain join their devices. A less-extreme version of control is called a workplace join, which can be thought of as a relaxed version of a fully domain-joined device.

Any IT administrator’s goal should be to ensure secure, encrypted communication between corporate resources and the device itself. Installing a device certificate as part of the provisioning process is one way for a corporation to safely and securely manage the device.

Workplace Provisioning

The first goal of this provisioning process is to authenticate a user against a trusted directory service. Successful device provisioning (or registration) results in a JSON-based token on the device. This token helps ensure secure communication between users and the corporate network (see Figure 2).

Workplace Provisioning Helps Authenticate Users
Figure 2 Workplace Provisioning Helps Authenticate Users

Layered Identity

Thinking about a spectrum of security levels is prudent (see Figure 3). Some corporate information is simply more confidential. Extra measures are often needed to protect that extra-sensitive data.

The Spectrum of Security Levels
Figure 3 The Spectrum of Security Levels

Most of us are already familiar with user authentication. At that most basic level of security, a user logs in with his username and password. The second level is device authentication, possibly enforcing a multi-factor authentication approach. By combining the user identity and the device identity (using an SMS challenge, for example), you can then form a compound identity.

Network Location Awareness

Another important concern when running applications on personal devices is Network Location Awareness (NLA). This means when a request comes in for a protected network resource, you can determine whether that request originated from outside the corporate network. NLA provides an extra layer of protection because it helps enforce additional rules, such as multi-factor authentication for requests generated outside the corporate network.

To implement network location transparency typically means you create some sort of proxy Web service in a DMZ. A DMZ is a network that exposes an organization’s external-facing services to a larger and untrusted network, like the Internet. You can use these proxies to trigger additional rules and insulate private resources on a network from outside access. Microsoft has specific technologies that enable these scenarios. Learn more about them at bit.ly/1v50JPq.

Support Identity with Native iOS Code

We will illustrate some low-level techniques to leverage native iOS capabilities. Before diving into that, however, we’ll provide some content around Azure Mobile Services. Azure Mobile Services provides several commonly required capabilities to client programs. Client programs can be native iOS, Android, Windows Phone, browser-­based HTML/JavaScript or Windows. 

Any client platform that can call a REST API can leverage Azure Mobile Services. It provides varying levels of library support across those supported clients. Other capabilities include federated identity, access to storage, offline data sync and push notifications. Some capabilities are implemented in the back end, others in the front end. And you can use either the Microsoft .NET Framework or Node.js as the back end. 

One of the more challenging capabilities to implement is storing a security token on an iOS device. The token is initially provided by Azure Mobile Services. The OS needs to protect the token and it needs to be encrypted. Luckily, the keychain mechanism built into the iOS SDK provides this capability. It lets you securely store a token on an employee’s device. This is a purely native approach, meaning the code isn’t really reusable.

There are advantages to storing a security token locally on the device. The most important is that it lets users access the application without logging in every time. Azure Mobile Services applications may leverage any or all of several security token providers or identity providers, such as Active Directory, Azure Active Directory, Facebook, Twitter and others.  Each one provides basic authentication, but they’re unique in other ways. 

One way they’re different is the ability to expire tokens. Active Directory and Azure Active Directory allow for this, but Twitter does not. This ability to expire a token is important for authentication that grants access to corporate resources, so Active Directory and Azure Active Directory are ultimately better choices for this level of access than Twitter.

In the spirit of “start simple,” we’ll describe the process using Twitter authentication in this article, then cover Azure Active Directory in a future article. Xcode is the IDE used to develop iOS applications. It’s somewhat analogous to Visual Studio, but less sophisticated and capable. The traditional language to code iOS applications is Objective-C.

To illustrate these techniques, start with the tutorial at bit.ly/1vcxHMQ. Add federated authentication leveraging Twitter identity provider services. The tutorial includes both back-end and front-end modules. You can select either back end (.NET or JavaScript) as you follow along. Take the Objective-C pathway for the front end. We’ll borrow some code from another sample project (iOS-LensRocket) on GitHub to support the KeyChain feature.

Not many changes were needed to the front-end Xcode project provided by Azure Mobile Services. All we need to do is add the KeyChain code and security features from the security.framework library. When a user starts the application, basic token management logic is applied. The application starts by checking for a token by making a call into the KeyChain API. If the token is present, it’s retrieved and used. The user won’t be asked to log in to Twitter again.

Here’s a summary of the code changes that we’ll make in the Xcode IDE:

  • Link to an additional library (find more guidance at bit.ly/1x7Ajzz)
  • Add a few files from iOS-LensRocket to support KeyChain functionality
  • Modify the controller code

Figure 4 demonstrates how we’ll use Azure Mobile Services and native iOS code to control access to a SQL database using a token cached on the device.

High-Level Steps for Storing Authentication Tokens on an iOS Device
Figure 4 High-Level Steps for Storing Authentication Tokens on an iOS Device

The tutorial will get you to the point of running a native iOS application that can read and write to a SQL database hosted in the cloud. You’ll have a working Xcode project written in Objective-C. However, it’s missing authentication—we’ll explain that later. The existing implementation uses an application key provided by Azure Mobile Services:

// Initialize the Mobile Services client with your URL and key.
MSClient *client =
  [MSClient clientWithApplicationURLString:@"https://msdnmagazine.azure-mobile.net/"
applicationKey:@"cctyYudYfxuczeRDMPcDBRCxDrOUIM73"];

The concern for this approach is obvious. Anytime you embed secrets into your application code, you expose yourself to security risks. What we really want to do is force the user to log in to perform database updates. However, we don’t want the user to have to log in constantly, so we’d like to store the authentication token on the device locally. We’ll configure the iOS app to retrieve the token when the application starts.

Most enterprise scenarios won’t embrace socially based identity providers, such as Facebook or Twitter. Nevertheless, it’s a useful place to start because we can demonstrate some of the core concepts for later leveraging on-premises identities with Active Directory. Also, many business applications leverage relational databases and Azure Mobile Services offers pre-built functionality to support them.

To get things started, you’ll have to do some basic tasks at the Azure Management Portal and the third-party identity provider (which in this case is Twitter). Create application metadata in the Twitter portal and the related application metadata in the Azure Mobile Services portal. Then get an application URL. Copy the application URL to Twitter and copy the Twitter API keys to Azure Mobile Services. This is how you bind an identity provider to an Azure Mobile Services application (see Figure 5).

The Relationship Between Azure Mobile Services and Twitter
Figure 5 The Relationship Between Azure Mobile Services and Twitter

This essentially involves creating mobile application metadata in the portal following these steps:

  1. Get URL for mobile app you created from Azure Management Portal
  2. Sign in and go to dev.twitter.com/apps/new
  3. Create a new Twitter app
  4. Get the API Key and API Secret for your Twitter app
  5. Return to Azure Management Portal
  6. Paste in API Key and API Secret from Twitter

Portal Work

As mentioned earlier, there are a couple of approaches to building your back end.  If you select the .NET Framework, you’ll have great control in Web API over use case authorization for all users, whether they’re authenticated or not. If you selected Node.js, the portal provides declarative and scripted approaches.

What we really need to do is go back to the Xcode IDE running on the Mac. We’ll use it to edit and compile the source code of the LOB iOS app that will run on the mobile device. 

We’ll make the following code changes in the Xcode IDE:

  • Add a library reference to security.framework.
  • Copy these four files from iOS-LensRocket at bit.ly/1pqvQ25:
    • KeyChainWrapper.h
    • KeyChainWrapper.m
    • LensRocketConstants.h
    • LensRocketConstants.m

There are three key functions/methods involved. The first is viewDidLoad, where we added a call to loadAuthInfo. This loads into memory a previously saved token from an earlier successful login. Here is where we’ll have to load the token from disk instead of forcing the user to log in again (see Figure 6).

Figure 6 Changes Made to Native iOS Code

#import "KeychainWrapper.h"  // Add this line.
- (void)viewDidLoad
{
  // Code omitted for brevity.
  [self loadAuthInfo];  // Add this line.
}
// Code omitted for brevity.
////////////////////////////////////////////////////////////////////////////////
//   Added viewDidAppear(), loadAuthInfo() below.
////////////////////////////////////////////////////////////////////////////////
// ----------------------------------------------------------------------------
// Event is viewDidAppear. When app becomes active, check credentials.
//
- (void)viewDidAppear:(BOOL)animated
{
  ////////////////////////////////////////////////////////////////////////////
  //  Check if current user is logged in. If not, log in to Twitter.
  MSClient *client = self.todoService.client;
  if(client.currentUser != nil)   {
    return;
  }
  [client loginWithProvider:@"twitter" controller:self animated:YES
    completion:^(MSUser *user, NSError *error) {
    [self saveAuthInfo];
    [self refresh];
  }];
}
// ----------------------------------------------------------------------------
// Save token locally.
// Leverage built-in iOS features called Keychain for user ID and tokenl storage
//
- (void) saveAuthInfo{
  // Save the userId
  [KeychainWrapper createKeychainValue:self.todoService.client.currentUser.userId
    forIdentifier:@"userid"];
  // Save the token itself
  [KeychainWrapper
    createKeychainValue:self.todoService.client.currentUser.
      mobileServiceAuthenticationToken
  forIdentifier:@"token"];
}
// ----------------------------------------------------------------------------
// Load the user ID and Token from the keychain. Avoid forcing user to log in again.
//
- (void)loadAuthInfo {
  NSString *userid =
    [KeychainWrapper keychainStringFromMatchingIdentifier:@"userid"];
  if (userid) {
    // Fetch the user ID and token from the Keychain.
    NSLog(@"userid: %@", userid);
    self.todoService.client.currentUser = [[MSUser alloc] initWithUserId:userid];
    self.todoService.client.currentUser.mobileServiceAuthenticationToken =
      [KeychainWrapper keychainStringFromMatchingIdentifier:@"token"];
  }
}

We also added the viewDidAppear function, which gets called when the application becomes visible or active. We use the MSClient object to check to see if the user is logged in. If the user isn’t logged in, we force a Twitter login and then save the credentials (token) to disk using the Keychain capabilities. This would more properly be implemented in viewDidLoad.

The saveAuthInfo and loadAuthInfo methods simply use the Keychain code to save and load the token to and from disk on the mobile device. You can read more about Keychain services at bit.ly/1qqcNFm.

You can follow a second tutorial on implementing authentication at bit.ly/1B3Av0k. You’d follow a similar process to allow for federation to Azure Active Directory, as opposed to Twitter:

  1. Get URL for mobile app you created from the Azure Management Portal
  2. Go to your Active Directory pages (also in the Azure Management Portal)
  3. Create a new application
  4. Get the Client ID and key
  5. Return to mobile app page in Azure Management Portal
  6. Paste in Client ID and key from Active Directory

We’ll go into more detail around federating to both Active Directory on-premises and Azure Active Directory in the cloud in a future article. In the meantime, you can see some great code samples at bit.ly/1slQMz2 and bit.ly/1mK1LQF.

Wrapping Up

As the pressure to support personal devices at the workplace continues to grow, it’s important for developers to better understand how to secure those devices and work with tokens. Implementing a username/password approach to authentication is often insufficient for truly confidential data.

To fully leverage all security capabilities on a device, you’ll often need to access native capabilities, as seen with iOS Keychain services. In upcoming articles, we’ll continue to explore the challenges facing IT leaders around mobile devices in the enterprise, focusing on identity, data synchronization and push notifications.


Bruno Terkaly is a developer evangelist for Microsoft. His depth of knowledge comes from years of experience in the field, writing code using a multitude of platforms, languages, frameworks, SDKs, libraries and APIs. He spends time writing code, blogging and giving live presentations on building cloud-based applications, specifically using the Microsoft Azure platform. You can read his blog at blogs.msdn.com/b/brunoterkaly.

Greg Oliver *joined the Microsoft Azure ISV organization in 2010. He spends most of his time helping companies with their migration plans and implementations. Most recently, he has been working with a popular consumer games company with their migration from a competing cloud provider. Prior to joining Microsoft, he was a technology partner in a startup company. *

Thanks to the following Microsoft technical expert for reviewing this article: Matthew Henderson