Authentication for Native or Hybrid Mobile Apps with Live Connect

As Satya Nadella likes to put it – we live in a mobile-first, cloud first world. While the web is ubiquitous, our connected lifestyle demands mobile applications that are powered by cloud services for ultimate mobility. Earlier we talked about Live Connect Authentication for Web applications; now let’s bring all that goodness to mobile – for any platform!

To recap, Live Services is what powers many facets of your Microsoft account benefits – like Profile information, Contacts, Calendars and OneDrive. Live Connect APIs provide a thin layer of RESTful services on top of Live Services for developers to integrate Live Services in their applications. In this article, we take a look at how to authenticate users of your mobile apps using Live Connect, and then to implement further integration with the user’s Microsoft account. We can do this from any native Windows, iOS or Android app, as well as from hybrid Cross-platform mobile apps.

Live Connect Authentication from Windows Apps

Integrating Live Connect APIs from Windows (Windows Phone and Window Store) apps is rather easy thanks to the Live SDK. You can either download the entire latest SDK or only get the NuGet package for Live SDK on Visual Studio projects where you need integration. In either case, the SDK provides easy wrappers for integrating with Live Connect RESTful endpoints, without having to worry about the underlying HTTP calls.

Let’s walk you through turning on Live Connect user authentication for a Windows Store app. I’m going to use a demo app that I wrote as a part of my Apress Windows 8 Development book; feel free to check it out if you want to write Windows Store apps using the XAML/C# stack.

The first step is to add a reference to the Live SDK DLL to be used inside our project, as shown below:

LiveSDKRef

I’m skipping over building the UI for the app for brevity. Just keep in mind, for something like a Microsoft account sign-in option for users, Windows 8/8.1 design guidelines suggest having such options as Settings integrated in the Charms bar, as shown below:

WindowsApp1

Now, before you turn on Live Connect user authentication, you have to head to the Live Connect App Management site and configure our app appropriately for Live Connect handshaking. Below is the C# code for leveraging the Live SDK to allow the user to sign in using their Microsoft account:

using Microsoft.Live;
private LiveConnectSession _session = null;

public async Task AuthenticateUserThroughLive()
{
  try
  {
      LiveAuthClient LCAuth = new LiveAuthClient("<Redirect Domain>");
      if (LCAuth.CanLogout)
          LCAuth.Logout();

      try
      {
          LiveLoginResult loginResult = await LCAuth.LoginAsync(new string[] { "wl.signin", "wl.basic", "wl.calendars", "wl.skydrive", "wl.skydrive_update" });
          if (loginResult.Status == LiveConnectSessionStatus.Connected)
          {
              this.LiveSession = loginResult.Session;
              // Any needed UI updates.
          }
      }
      catch (LiveAuthException)
      {
         // Handle exceptions.
      }
  }
  catch (LiveAuthException)
  {
     // Handle exceptions.
  }
}

You’ll notice the usage of the Microsoft.Live namespace for accessing the Live SDK features and the C# async-await pattern to make the Live Service calls asynchronous. The LoginAsync() method is used to fire up the user authentication, passing in the requested Scopes. You’ll notice that code is requesting several Scopes. A declared privacy policy is suggested in such cases so that the user knows exactly why the app is requesting this access. The app user sees the Microsoft account sign in pop-up (as shown below) if not already signed in or the permission access screen if using the app for the first time.

WindowsApp2

Once the user signs in and has agreed to grant permission to the requested Scopes, the LiveConnectSession object in our code is populated with content. It is this session object that contains the Authentication token, which identifies the user as well as access rights to his/her information. Moving forward, all subsequent Live Connect API interactions simply carry this token to the service every time until expiry.

Live Connect Integration from Windows Apps

We have now signed the user into our Windows Store app, without actually dealing with user authentication ourselves. Now sure, the same can be achieved through any other identity provider – like Facebook, Google or Twitter, but authenticating a user through their Microsoft account by using Live Connect APIs comes with a few, free benefits.

Now that the user has signed in and granted your app permission to access other user account features, you can access aspects of the user’s personal information. In the screenshot below, my app greets the user by name, fetches their profile picture, read their contacts, interacts with events on their calendar and navigates files/folders in their OneDrive. And this is not just for read access, your app could have write-access to this user data. How cool is that!

WindowsApp3

There is an app-level global object to hold the LiveConnectSession after the user signs in and appropriate UI placeholders to display content. Below is the code to greet the user by name:

private async void GreetUserByName()
{
    if (((App)Application.Current).LiveSession != null)
    {
      try
      {
         LiveConnectClient liveClient = new LiveConnectClient(((App)Application.Current).LiveSession);
         LiveOperationResult operationResult = await liveClient.GetAsync("me");
         dynamic result = operationResult.Result;
         if (result != null)
         {
             this.userInfoText.Text = "Hello " + result.name + "!";
             this.actionText.Text = "Sign out Now!";
         }
      }
      catch (LiveConnectException)
      {
         // Handle exceptions.
      }
    }
}

Did you notice usage of the me keyword in the GetAsync() call above? This is the shortcut to refer to the signed-in user. Here’s the code to read the user’s profile picture:

private async void FetchUserProfilePicture()
{
    if (((App)Application.Current).LiveSession != null)
    {
      try
      {
         LiveConnectClient liveClient = new LiveConnectClient(((App)Application.Current).LiveSession);
         LiveOperationResult operationResult = await liveClient.GetAsync("me/picture");
         dynamic result = operationResult.Result;

         BitmapImage image = new BitmapImage(new Uri(result.location, UriKind.Absolute));
         this.profilePicture.Source = image;
      }
      catch (LiveConnectException)
      {
         // Handle exceptions.
      }
   }
}

Here’s how to fetch the list of contacts from user’s Outlook account:

private async void FetchContacts()
{
   if (((App)Application.Current).LiveSession != null)
   {
     try
     {
         LiveConnectClient liveClient = new LiveConnectClient(((App)Application.Current).LiveSession);
         LiveOperationResult operationResult = await liveClient.GetAsync("me/contacts");
         dynamic contactsResult = operationResult.Result;

         List<dynamic> contactsList = contactsResult.data;
         this.contactsList.ItemsSource = contactsList;
     }
     catch (LiveConnectException)
     {
        // Handle exceptions.
     }
   }
}

Want to read events form the user’s Calendar? No problem, here’s the code:

private async void FetchCalendarEvents()
{
   if (((App)Application.Current).LiveSession != null)
   {
     try
     {
         LiveConnectClient liveClient = new LiveConnectClient(((App)Application.Current).LiveSession);
         LiveOperationResult operationResult = await liveClient.GetAsync("me/events");
         dynamic calendarEventsResult = operationResult.Result;

         List<dynamic> eventsList = calendarEventsResult.data;
         this.eventsList.ItemsSource = eventsList;
     }
     catch (LiveConnectException)
     {
        // Handle exceptions.
     }
   }
}

Your app can also read the names of files and folders inside the user’s OneDrive, as well as navigate to any nested level. Here’s the basic code to read OneDrive content (earlier called SkyDrive):

private async void FetchSkyDriveInfo()
{
   if (((App)Application.Current).LiveSession != null)
   {
     try
     {
        LiveConnectClient liveClient = new LiveConnectClient(((App)Application.Current).LiveSession);
        LiveOperationResult operationResult = await liveClient.GetAsync("me/skydrive/files");
        dynamic skydriveContentResult = operationResult.Result;

        List<dynamic> skydriveContentsList = skydriveContentResult.data;
        this.skyDriveList.ItemsSource = skydriveContentsList;
     }
     catch (LiveConnectException)
     {
        // Handle exceptions.
     }
   }
}

Want your user to take a photo in your app and upload that to his/her OneDrive? The code below allows the user to select a picture through a FilePicker API and upload to OneDrive (root by default) content.

private async void fileUpload_Click(object sender, RoutedEventArgs e)
{
   try
   {
      var picker = new Windows.Storage.Pickers.FileOpenPicker();
      picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
      picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
      picker.FileTypeFilter.Add(".png");

      Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
      if (file != null)
      {
         LiveConnectClient liveClient = new LiveConnectClient(((App)Application.Current).LiveSession);
         await liveClient.BackgroundUploadAsync("me/skydrive", "MyUploadedPicture.pnsg", file, OverwriteOption.Overwrite);
      }
   }
   catch (LiveConnectException)
   {
      // Handle exceptions.
   }
}

The Live Connect SDKs offer tremendous power and flexibility to the developer to integrate their apps with user’s Live Services. But be careful not to undermine user trust and implement these Live Service integrations only where appropriate, with complete user visibility.

What about other platforms?

So far, you’ve seen that a Windows Store app works nicely with Live Connect to facilitate user authentication and integrates with other Live Services, if allowed by the user. If you are making a Windows Phone app, the code we walked through above works seamlessly as is. Simply get the appropriate Live SDK, reference it and you’ll be up and running integrating Live Connect with Windows Phone apps. In fact, the Live Services integration code we discussed works for any modern .NET applications – web, desktop or mobile.

But what about mobile platforms outside of Windows that have a bigger marketshare? Sure, bring it on! If writing a native iOS app with Objective-C, you can grab the Live SDK for iOS, reference the SDK and follow the detailed integration walkthrough to have your iOS app work seamlessly with Live Services. Writing a native Android app in Java? Same great story – grab the Live SDK for Android and follow Android integration steps to work with Live Services. Bottom line, Live Connect APIs can be consumed from any platform, thanks to the RESTful endpoints, although the dedicated SDKs for Windows, iOS and Android help a lot.

Let’s talk Hybrid Cross-Platform Mobile Apps

You can build native mobile apps in Windows, iOS and Android, and integrate seamlessly with Live Services. But while native apps do provide a great user experience, it calls three very different code bases in C#, Objective-c/Swift and Java! That is a lot for a single indie developer to learn to take on by himself/herself. And for enterprises, this means maintaining three different development teams with widely varying skillsets. It’s 2014, and you want your app on every mobile platform.

The solution often is hybrid cross-platform mobile apps. You can re-use your web skills to build mobile apps with a single codebase, but one that runs on every platform with an App Store presence. Telerik AppBuilder offers end-to-end tooling for hybrid cross-platform mobile development. It provides the freedom to use any IDE (Visual Studio, browser, windows application, Sublime Text or Command Line) with robust simulators for each mobile platform and easy device deployment options.

Let’s integrate Live Connect user authentication for hybrid mobile apps. You’ll notice one difference in the way you configure your app with Live Connect – unlike web applications, mobile apps do not have a URL. Here’s the workaround as quoted from MSDN documentation:

When you get a client ID from the Live Connect app management site, leave the Redirect Domain field blank, and select Yes for the Mobile client app option. By doing so, you configure your app to use a special redirect URL (https://login.live.com/oauth20_desktop.srf), which enables the app to handle redirects after the user has given authorization and facilitates refreshing the access token.

Let’s begin from scratch with the AppBuilder browser-based client and a fresh default project template. Our goal is simply allow the user to sign in to the hybrid mobile app using their Microsoft account. Our index.html (i.e. our starting page) UI is just a simple sign-in button, as shown in the markup below. There is a label placeholder to greet the user by name once he/she signs in.

XPlatIndex

Now, we will invoke the RESTful endpoint of the Live Connect APIs directly to authenticate the user. Since this is an HTTP GET call, it is best done through a web browser inside your hybrid app. AppBuilder supports the Cordova InAppBrowser plugin. All you have to do is go into your project’s properties and enable the InAppBrowser plugin, as shown below:

XPlatPlugins

Let’s look at the JavaScript code for the main.js file (don’t worry, we’ll break this down in pieces after).

document.addEventListener("deviceready", onDeviceReady, false);

document.addEventListener("touchstart", function() {
}, false);

function onDeviceReady() {
        var app;
        navigator.splashscreen.hide();
        app = new Application();
        app.run();
}

function Application() {
}

Application.prototype = {
            run: function() {
                 var that = this,
                 signInButton = document.getElementById("signInButton");
                 signInButton.addEventListener("click", that.signInPopup);
},

signInPopup:  function () {
                 var inApp = window.open("https://login.live.com/oauth20_authorize.srf?client_id=<YOUR_CLIENT_ID>&scope=wl.signin&response_type=token&redirect_uri=https://login.live.com/oauth20_desktop.srf", "_blank");
                inApp.addEventListener('loadstart', function(event)
                {
                    if (event.url.indexOf("#access_token") > -1){
                        var startOfAccessToken = event.url.indexOf("#access_token");
                        var endOfAccessToken = event.url.indexOf("&");
                        var accessToken = event.url.substring(startOfAccessToken+14, endOfAccessToken);
                        var userDataLookUpURL = "https://apis.live.net/v5.0/me?access_token=" + accessToken;
 
                    $.ajax({
                      url: userDataLookUpURL
                      }).done(function(response) {
                         var userName = response.first_name + " " + response.last_name;
                         document.getElementById('signInButton').style.display='none';
                          document.getElementById("userInfo").innerText = "Hello " + userName + "!";
                });

                alert('Login success!');
                inApp.close();
              }
           });
        }
}

Some of the initial code is boilerplate to get your application set up. Notice the onDeviceReady event handler indicating the Cordova is loaded up and ready to work on the HTML DOM. We are simply adding a click event handler to our sign-in button and taking the user to a specific URL using the window.open() method. The window launches inside the InAppBrowser and the URL points to the Live Connect authentication RESTful endpoint. Notice how we pass along the app’s ClientID, scopes and use a specific Redirect URI, where we will later go and grab our authentication token from. Once the user signs in with their Microsoft account and provides consent to the scopes, Live Connect makes an HTTP POST back to the Redirect URI and includes the Access Token for future correspondence. We can listen in via the loadstart event of our InAppBrowser and grab the access token when done. There’s a little JavaScript code (not the most elegant) to parse out the access token. Once we have that, we’re golden! We can now integrate with all of the permitted Live Service features from the user’s Microsoft account, including access to contacts, calendars and OneDrive. You can see the code where we make another HTTP GET call using the me shortcut to fetch and greet the user by name, passing in the access token captured before.

Let’s see this running on a real device. First, let’s grab the AppBuilder Companion app, available for iOS, Android and Windows Phone. I already have the iOS companion app ready for deploying to my little iPod Touch. Fire up an AppBuilder Build for our project. When done, this generates a QR Code for easy deployment to devices. Did you know the AppBuilder companion app has an in-built QR Code scanner? Yep, just as shown below; simply swipe with two fingers from left edge.

XPlatSSO2

Here’s the user interaction from our hybrid mobile app, as the user steps through authentication himself/herself and allowing access to the requested Scopes.

XPlatSSO1   XPlatSSO3

XPlatSSO4   XPlatSSO5

As you can see, the InAppBrowser seamlessly displays the authentication and permission screens, which are automatically rendered responsively for each device. Once we have the access token, we show a pop-up to the user (completely optional), close the InAppBrowser and greet the user by name.

Once you have the access/authentication token, you can now go ahead and integrate your app with other Live Service benefits for personalization. And the best part – this version is a hybrid cross-platform app solution that works for every platform. A single codebase can support the iOS, Android and Windows platforms.

Conclusion

In this article, we started with integrating our Windows apps with Live Connect user authentication, but we soon discovered that it is just as easy to tap into other Live Services benefits – like the user’s contacts, calendars and OneDrive. But why stick to just Windows? Live SDKs are available for native iOS and Android application development to carry all the Live Connect goodness to other platforms. If building multiple native apps once for each platform isn’t your cup of tea, we also saw how to integrate Live Connect inside a cross-platform hybrid mobile app, using simple JavaScript code that interacts with RESTful endpoints to bring out the Live Services integration benefits. Happy coding!

AppBuilderBanner

Comments