July 2014

Volume 29 Number 7

Modern Apps : Authentication and Identity in Windows Store Apps

Rachel Appel | July 2014

Rachel AppelAn overwhelming number of apps and Web sites now require some sort of login or credentials. One reason is that many of them customize the experience based on saved user preferences. Because so many sites and apps require user sign in, you need to make it easy for users to do so. In this article, you’ll learn the basics of app authentication on the Windows platform by enabling Microsoft Account or third-party login, as well as supplemental authentication methods such as smart card or biometric authentication.

Modern App Authentication and User Identity

More often than not, gathering user credentials is more of a pain to the user than an enriching experience. Therefore, when you must store user credentials, you want to do so in a way that keeps things secure, yet maintains ease of use.

Using an independent credential provider such as Microsoft Account (formerly Windows Live ID), Facebook, or OAuth is a great way to lean on a trusted entity to manage and store user information. This still provides users with a persistent, individualized UI. Also, let’s face it—a user simply doesn’t remember all his passwords, especially in sites and apps he uses infrequently. Asking a user to create and remember another set of credentials just adds friction to his experience. That alone can cause a drop in your app store ratings, which is the opposite effect of what you want.

On the developer side, storing user credentials means you have to write more code, tests and bug fixes than you would if you were using something such as a Facebook login. There’s also the potential for security breaches when storing login data in local databases. You can alleviate stress for both users and yourself by using a trusted entity such as Microsoft, Facebook, Twitter, OAuth or any credible third-party credential service. The service stores user credentials and private information using proper algorithms so it remains secure. All you have to do is make some calls to the API, and that does all the heavy lifting.

Using Microsoft Account

When using Microsoft Account, users expect the login experience to be similar and consistent with Windows login. Instead of creating your own UI controls for collecting the information, you should use those that come with the Microsoft Account APIs. Fortunately, that also makes it easier to code. Coding login information is a boring task you can and should abstract with APIs such as the Microsoft Account APIs.

If you’re going to require a login, show the login UI upon starting the app. If the user can stay signed in between sessions or doesn’t have to log in, add that to the Settings. Also, don’t forget to make sure the user can sign out. That’s so easy to forget, as many users prefer to stay signed in to favorite Web sites and apps.

This can be an issue if someone needs to borrow a phone or device. If he signs in and can’t sign out, the next person could poten­tially use the app and masquerade as the first one. On the other hand, the first person may never be able to share his device due to not being able to sign out in the first place.

Be sure to keep sign-in status where a user can readily see it from all screens in your app. This doesn’t have to be a boring text update. You can show the user’s avatar or perhaps some photos from his OneDrive photo storage (if using Microsoft Account). Be as creative as you want, as long as the user can see and change his status with ease. A common technique is to show the user’s avatar thumbnail in the top right corner of the app.

Microsoft Account Authentication

Using Microsoft Account authentication gives you a fluid sign-on experience to all Microsoft Live services, such as OneDrive, Outlook.com, an MSDN subscription, Xbox, and even Windows 8 devices and apps.

To be able to use services that may contain sensitive user information, you must register the app with the Microsoft Dev Center online (bit.ly/1egpvHx). Doing so lets you use Microsoft Account services in your app so you can connect users to various resources.

Because you’re working with services that access personal data, you have to provide a clear privacy statement accessible within the app. If you need help writing a privacy policy, you can use myapppolicy.com or w8privacy.azurewebsites.net to help you build one. Once you’ve established a privacy policy, you can display it with a Settings flyout.

Finally, you need to deliver code to sign people in and out. You can do this with a Flyout control that contains a sign-in button (this changes to a sign-out button when signed in). The buttons launch dialogs to perform the corresponding operations of signing in or out. Figure 1 shows the XAML that creates an Account Settings Flyout.

Figure 1 This Code Creates the Account Settings Flyout

<SettingsFlyout
  x:Class="App.Account"
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="using:App"
  xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="d"
  IconSource="Assets/SmallLogo.png"
  Title="Account"
  d:DesignWidth="346">
  <StackPanel x:Name="accountSettings">
    <Button x:Name="SignInButton" Click="SignInClick" Content="Sign in" />
  </StackPanel>
</SettingsFlyout>

As you can see, it’s a control with a button. The button is what the user will use to launch the login interface. It’s a customary practice to put a sign-in button in a Flyout. To learn more about creating Settings Flyouts, see “Mastering Controls and Settings in Windows Store Apps” (bit.ly/1hy7Fk2). The code that signs users into your app from the click event of the sign-in button should look something like this:

private async void SignInButton_Click(object sender, 
  RoutedEventArgs e)
{
  LiveAuthClient authClient = new LiveAuthClient();
  LiveLoginResult authResult =
    await authClient.LoginAsync(new List<string>() 
   { "wl.signin", "wl.basic"  });
  if (authResult.Status == LiveConnectSessionStatus.Connected)
  {
    // Perform post authentication duties
  }
}

This displays the Microsoft account sign-in screen (often called the login consent page), if the user hasn’t already signed in (see Figure 2). As you can see, it doesn’t take much code to make the login process happen. You can use the Session property of the LiveAuthClient to query for session status throughout the app.

The Microsoft Account Sign-in Screen
Figure 2 The Microsoft Account Sign-in Screen

You can perform the same activities with HTML and JavaScript, but the steps are slightly different. First, reference the Windows Live SDK with the Add Reference command. Then, as is customary in HTML development, reference the scripts with the <script> tag in your HTML document, like this:

<script src="///LiveSDKHTML/js/wl.js"></script>

However, you might want to use the debug version during development. In that case, you can use the following reference:

 

<script src="//js.live.net/v5.0/wl.debug.js"></script>

Figure 3 contains the WinJS code that signs in a user. You need to call WL.init and WL.Event.subscribe so you can initialize the Microsoft Account, as well as subscribe to an event that happens upon login. XAML apps don’t require this initialization. In the login event, you can display connection status or do whatever is required just after logging in.

Figure 3 The WinJS Code That Signs the User In

(function () {
  "use strict";
  WL.init();
  WL.Event.subscribe("auth.login", loginComplete);
  document.querySelector("#SignInButton").addEventListener("click",
    function () {
      login();
    });
  function loginComplete() {
    WinJS.log("User has signed in!")
  }
  function login() {
    var session = WL.getSession();
    if (session) {
      WinJS.log("You are already signed in!")
    }
    else {
      WL.login({ scope: "wl.basic" }).then(
        function () {
          // Perform post authentication duties
        },
        function (response) {
          WinJS.log("Could not connect, status = " + response.status);
        });
    }   
  }
})();

The code in Figure 3 does the same thing as its XAML counterpart—it actually logs in a user. Regardless of the language you use, the wl.login method requires you to pass in a scope. A scope is a permission level, or a scope of where and what an app can do on behalf of the user. As you might imagine, scopes are user-­controlled. You can try to do anything you want while posing as the user, but the Windows Runtime will force you to obtain user consent before proceeding.

Web Authentication Broker (OAuth)

Using a centralized and objective third-party credential service such as Microsoft Account, Facebook, Twitter, LinkedIn, OAuth and so on is a good authentication strategy. Users are more likely to remember their passwords for sites they visit frequently or prefer more. Using a reputable authenticator also means less infrastructure code on which you have to focus, and more time for business logic or UI work.

Web Authentication Broker is one way to easily perform authentication. With Web Authentication Broker, you don’t have to deal with the hassles of securely storing user information. Instead, you properly encrypt all personal information. Web Authentication Broker is a liaison between an app and an authentication provider. It also enables single sign-on across multiple apps.

Call the Web Authentication Broker in code to retrieve and display a dialog box or Web page from a specific authentication service such as Facebook (see Figure 4). The dialog is the same sign-in screen the user would normally see when logging into the provider’s Web site or app. In most cases, you can customize it so it feels like a natural part of your app.

Figure 4 Signing in with Web Authentication Broker

async public Task<string> WebAuthenticate(){
  string startURL =
    "https://<providerendpoint>?client_
    id=<clientid>&scope=<scopes>&response_type=token";
  string endURL = "https://<appendpoint>";
  System.Uri startURI = new System.Uri(
    "https://<providerendpoint>?client_
    id=<clientid>&scope=<scopes>&response_type=token");
  System.Uri endURI = new System.Uri(
    "https://<appendpoint>");
  string result;
  try
  {
    var webAuthenticationResult =
      await WebAuthenticationBroker.AuthenticateAsync(
      WebAuthenticationOptions.None,
      startURI,
      endURI);
    switch (webAuthenticationResult.ResponseStatus)
    {
      case WebAuthenticationStatus.Success:
        result = webAuthenticationResult.ResponseData.ToString();
        break;
      case WebAuthenticationStatus.ErrorHttp:
        result = 
          webAuthenticationResult.ResponseErrorDetail.ToString();
        break;
      default:
        result = webAuthenticationResult.ResponseData.ToString();
        break;
    }
  }
  catch (Exception ex)
  {
    result = ex.Message;
  }
  return result;
}

Smart Card Authentication

Microsoft has long used smart cards as a way to authenticate VPN connections to the company’s networks, as well as provide secure access to buildings and other corporate resources. Now you can easily incorporate smart cards into your software. The Windows.Devices.SmartCards namespace contains classes such as SmartCard and SmartCardConnection that let you write code to authenticate and manage smart cards. While smart cards may seem overly complicated, they’re not. If you wanted to verify what cards are currently located in the reader, for example, you can write code similar to the following:

string selector = SmartCardReader.GetDeviceSelector();
DeviceInformationCollection devices = 
  await DeviceInformation.FindAllAsync(selector);
foreach (DeviceInformation device in devices)
{
  SmartCardReader reader =
    await SmartCardReader.FromIdAsync(device.Id);
  IReadOnlyList<SmartCard> cards = await reader.FindAllCardsAsync();
}

Notice that Windows.Devices.DeviceInformation obtains infor­mation about each device. In Windows, this is a standard way to query for hardware. The Windows Runtime exposes many of the objects that communicate with hardware that were previously unavailable to .NET developers.

Biometric Authentication

Although it’s unlikely you could use another form of authentication besides the standard username/password technique because many devices and machines don’t support the hardware, you can use a stored and registered fingerprint to read software. It’s a great feature and quite helpful to those who may have accessibility needs.

Consider the Lenovo Carbon Touch X1 laptop computer. This model has a fingerprint reader built into the laptop near the keyboard. With Windows 8 biometric authentication, you can use this type of authentication. Figure 5 shows the code you would use for biometric authentication.

Figure 5 Fingerprint Authentication

var availability = 
  await UserConsentVerifier.CheckAvailabilityAsync();
if (UserConsentVerifierAvailability.Available) {
  var consentResult = 
  await UserConsentVerifier.RequestVerificationAsync(userMessage);
}
var consentResult = 
  await UserConsentVerifier.RequestVerificationAsync(userMessage);
switch (consentResult)
{
  case UserConsentVerificationResult.Verified:
    returnMessage = "Fingerprint verified.";
    break;
  case UserConsentVerificationResult.DeviceBusy:
    returnMessage = "Biometric device is busy.";
    break;
  case UserConsentVerificationResult.DeviceNotPresent:
    returnMessage = "No biometric device found.";
    break;
  case UserConsentVerificationResult.NotConfiguredForUser:
    returnMessage = "The user has no fingerprints registered.";
    break;
  case UserConsentVerificationResult.RetriesExhausted:
    returnMessage = "Too many failed attempts.";
    break;
  case UserConsentVerificationResult.Canceled:
    returnMessage = "Fingerprint authentication canceled.";
    break;
  default:
    returnMessage = "Fingerprint authentication is currently unavailable.";
    break;
}

The code in Figure 5 displays a modal dialog much like the one in Figure 2, except it will prompt the user to scan their finger on the biometric device during the call to CheckAvailabilityAsync. Once the user scans his finger, you can query the consent result to see if it’s a verifiable scan.

Signing Out

Using Microsoft Account, you can deliver a rich and consistent experience that integrates seamlessly into Windows 8. Now you have a variety of authentication providers, which you should use before building your own. Whether you use Twitter, Facebook, Microsoft, or others, they’ve already addressed the challenges and issues that come with securely managing private user information. Those providers also keep security up-to-date. This makes reputable third-party validation the best choice for modern app authentication.

Unless it’s an absolute must, don’t create your own algorithms to store private user information. Use a service such as Credential Locker if you need to retain that information. You can hang onto user credentials safely with Credential Locker. This gives the app a way to automatically sign in a user across app sessions, because her credentials are in a vault in the cloud, which enables roaming.

Roaming is a must-have feature when your app runs on multiple devices (such as a tablet and phone). Using Credential Locker, you can securely lock down credentials, yet pass them between versions of your app, as well as social networking or other external sites. Moreover, you don’t have to maintain infrastructure to store user information. You can find more details about the Credential Locker at bit.ly/1qFxfmG.

With augmented authentication like biometrics, you’re sure to have the highest-rated apps in the store. The UI is modern, easy to use, and has all the bells and whistles. Not all devices will have the exact same authentication peripherals, so don’t rely on something like biometrics as the sole means of authentication.


Rachel Appel is a consultant, author, mentor and former Microsoft employee with more than 20 years of experience in the IT industry. She speaks at top industry conferences such as Visual Studio Live!, DevConnections, MIX and more. Her expertise lies within developing solutions that align business and technology focusing on the Microsoft dev stack and open Web. For more about Appel, visit her Web site at rachelappel.com.

Thanks to the following Microsoft technical expert for reviewing this article: Frank La Vigne