Telerik blogs
Do you have a Microsoft account? Yes, the same consolidated account that powers your Outlook email/contacts/calendars, OneDrive, Xbox, Windows 8 and Windows Phone devices, along with a slew of other Microsoft services. Millions of people do. Chances are, your application's users probably also have a Microsoft account. This presents a potential opportunity. Live Services is what powers many facets of your Microsoft account, like profile information, contacts, calendars and OneDrive. These services are very familiar for many users, and when you're able to leverage these same services, users can feel right at home within your application. Enter Live Connect APIs, which are a thin layer of RESTful services on top of Live Services that allows developers to integrate Live Services into their applications. This is possible from any type of application - web, whether desktop or mobile, and across any platform. In this article, we'll take a quick look at Live Connect APIs and then a deep-dive into using them for user authentication within a web application.

Live Connect APIs and SDKs

Live Connect is a collection of APIs that Microsoft offers for easy integration of your applications with Live Services – the ones that power the user's Microsoft account authentication, Outlook and OneDrive. This allows users to engage with services they already use, which can, in turn, increases application usage by offering users something that is familiar and leveraging existing accounts rather than forcing them to create new ones. Live Connect provides an API layer through RESTful services and uses industry-accepted open standards. Here's a breakdown of the standard technologies in use:

  • OAuth 2.0 – Live Connect uses the latest standard OAuth protocol for authenticating user credentials. This includes implicit grant flow, authorization code flow and sign-in control flow.
  • REST – All Live Connect services follow the RESTful architectural pattern and honor HTTP verbs of GET, PUT, POST and DELETE.
  • JSON – Live Connect APIs exchange information between client-services through the standard JSON format for serialization/deserialization.
Now, open standard usage means that Live Connect APIs are usable from any platform and can be used to build any type of client application. But coding against a set of RESTful services often involves a bit of integration work on the network level. Enter Live Connect SDKs – software wrappers for easy consumption of Live Connect RESTful services. Here are the platforms where Live Connect has dedicated SDKs:
  1. Web – Plain JavaScript SDK
  2. .NET – For all types of .NET apps, including Windows Store, Windows Phone
  3. iOS – For native Objective-C iOS apps
  4. Android – For native Java Android apps
That covers just about everything across platforms, doesn't it? Grab the appropriate SDK and integrate with Live Services. The Live SDK Developer Guide is a good place to start.

Let's talk Authentication

If you are an Enterprise application developer, you may have custom authentication for users to sign in to your application; there may be complex user groups/roles controlling access to different application features. Or, if you are a service provider (like Amazon or Barnes & Noble, etc.), you may have complex subscriptions or benefits tied to the user's account after he/she signs in to your application. Beyond the above reasons, however, I believe we app developers need to get out of the business of authenticating users. Security is tricky business, since you have to store user credentials with lot of care. Also, you are making your users remember one more User ID/Password to get into your application, on top of the dozens they already have to remember. It might be worth trusting some established identity providers – Microsoft, Twitter, Facebook, Google etc. - to authenticate your users. They deal with user security and you get an innocuous authentication token through OAuth once the user signs in. In the next few sections, we take a look at how you can use Live Connect SDKs/APIs to sign the user into your web app, using their Microsoft account. The Microsoft account sign-in through Live has the additional benefit of integrating with the user's Contacts, Calendars and even OneDrive!

Configuration

Before we dive into looking at user authentication across several platforms, it is important to set up your application with Live Connect. This is where you create and configure your app, so that Live Connect knows how to do the handshakes with the user and hand you back the all-important authentication tokens. Look up details about configuring your application and head to the Live Connect App Management site to set up your application. Make sure to set up your Redirect Domain (where Live Connect posts back the authentication token after the user authenticates) when appropriate, and make note of the Client ID/Secret.

Authentication for Web

Say you are writing a web application with ASP.NET, you can easily integrate the JavaScript Live Connect SDK to allow the user to authenticate into your app through their Microsoft account. Here's how... Let's start with the default MVC template, as shown below.

WebProject-700x1024

Add the following script reference in my _Layout.cshtml, for global availability. This is the Live Connect web SDK available as a JavaScript file:
<script src="//js.live.net/v5.0/wl.js"></script>
Next, tweak the _LoginPartial.cshtml file to roll in Live authentication, instead of the built-in ASP.NET one. Here's the code:
<div class="nav navbar-nav navbar-right" style="padding-top: 15px;">
<div id="signin"></div>
<label id="info" style="color: white;"></label>
<br/>
<a id="morescopes" style="color: white;" onclick="morescopes_onclick()"></a>
</div>

<script>
WL.Event.subscribe("auth.login", onLogin);

WL.init({
        client_id: "<YOUR_CLIENT_ID>",
        redirect_uri: "<YOUR_REDIRECT_URL>",
        scope: "wl.signin",
        response_type: "token"
});

WL.ui({
       name: "signin",
       element: "signin"
});

function onLogin (session) {
         if (!session.error) {
            WL.api({
               path: "me",
               method: "GET"
            }).then(
               function (response) {
                         document.getElementById("info").innerText =
                             "Hello, " + response.first_name + " " + response.last_name + "!";
                         document.getElementById("morescopes").innerText =
                             "Get more stuff.";
               },
               function (responseFailed) {
                         document.getElementById("info").innerText =
                             "Error calling API: " + responseFailed.error.message;
               }
           );
         }
         else {
              document.getElementById("info").innerText =
                      "Error signing in: " + session.error_description;
         }
   }

</script>
Some simple markup and little JavaScript is all that's needed to allow WL (i.e. Windows Live) to do user authentication. Note the ui() method which renders a simple Sign-in/out button. Also, the code scope: "wl.signin" actually declares a Scope, which is like a permission to sign the user in. We'll look at this in a little more detail in just a bit. For now, our goal is to allow the user to sign in through their Microsoft account and welcome them by name. Fire up our web application, and this is what you should get:

WebApp1-1024x698 
We get the templated ASP.NET project website, with the exception of the Windows Live sign-in button in top right corner. Here's what the user sees on trying to sign in:

WebApp2-1024x698

This UI to sign in is not something you have to create, as it's coming from a redirect to Microsoft's Live authentication services. Once the user provides his/her Microsoft account credentials, here's the next screen in the process:

WebApp3-1024x698

In this step, Live Connect is essentially asking the user – "Hey, this particular app is trying to have the following access... do you approve?" This access request list is driven directly by the Scopes your app is requesting permission to use. Live Connect documentation lists detailed information on Scopes and their permissions.
Caveat: Live Scopes provide granular access lot of information that is tied to the user's Microsoft account. Developers can request app permissions to not just read, but also write access to the user's Contacts, Calendars, Profile and OneDrive. This is very personal information for any user and must be requested responsibly. Only ask permission for the things you need. If you need more permissions, you can always add more Scopes later, as we'll see in a bit.
Once the user signs in through his/her Microsoft account and grants access to requested Scopes, the user is returned to our web application. Your WL object on the client side now has access to the all-important authentication token – a combination of user authentication information and the granted Scopes. This token can be used in all subsequent communication with the Live Connect APIs and the user will not be asked to sign in again or provide permission to Scopes. Tokens do have a lifetime, however, after which they expire and your app will just need to refresh the token from Live Connect. With the token in hand, we can now make WL.api() method calls to get access to what's needed, provided we have requested the appropriate permission. The me shortcut refers to the signed-in user and reading profile information is an HTTP GET call away. Here's the result once the user comes back to our web application.

WebApp4-1024x698

You can see that we're now able to greet the user by name, although our app did not actually authenticate the user. You don't have to use the built-in Windows Live sign-in button. User authentication can be triggered from any HTML markup through JavaScript. To prove this, let's add a event handler when the user clicks on the link under the greeting, named "Get more stuff". Here's the code:
function morescopes_onclick() {
           WL.login({
           scope: ["wl.signin", "wl.basic"]
      }).then(
         function (session) {
           document.getElementById("morescopes").innerText =
           "All done here.";
      },
      function (sessionError) {
          // Some error handling.
      }
  );
}
We are invoking the WL.login() method here to trigger authentication. Had the user not just signed-in, he/she would see the Microsoft account sign in screen. However, you'll notice that we requested one more additional scope, wl.basic, which provides us access to basic user profile information and contacts. Since this is more than what the initial authentication and its corresponding token were granted for, Live Connect is smart enough to throw up another access request screen, requesting additional user permission, as shown below.

WebApp5-1024x698

Now, all of the code that you've seen so far is plain JavaScript, which has a huge advantage. Although I started with a vanilla ASP.NET MVC project, this Live Connect user authentication really works from any web platform, since all we're dealing with here is plain HTML markup and JavaScript. Once the user authenticates through their Microsoft account and provides permissions against the Scopes our app has requested...voila! The WL client-side JavaScript object now has an authentication token, which will be used in all subsequent Live Connect API calls. Your application gets to integrate with Live Services to have read/write access to user data and even OneDrive. Also, if your mobile app has a companion website or the other way around, you can cache the authentication token for use across multiple platforms; the user gets a streamlined Single-Sign-On experience. How cool is that?
The little demo you saw above, based on vanilla ASP.NET template with only the Live authentication piece added, is actually live hosted as is in a small Azure website. Feel free to give it a spin at http://liveconnectsso.azurewebsites.net and see it greets you by name once you sign in with your Microsoft account. Also, if you are testing your web apps locally, the redirect URL for Live Connect to come back with an authentication token needs a little domain mapping; this means tweaking the system host file and is detailed at the bottom of this walkthrough.

Conclusion

In this article, we unpacked Live Connect, the RESTful services layer that allows easy integration with Live Services from our applications. We looked at how to enable user authentication through Microsoft account from web applications, simply using JavaScript. The Scopes allow for granular permissions that allow yout application to leverage more of the user's personalized content through Live Services. Impressed? Now go ahead and turn on Live Connect user authentication for your web application - one less thing for you to worry about! And stay tuned for the next part of this article where we talk Live Connect integration for Mobile apps. After all, we are living in a cloud-first, mobile-first world; and we can pull off rich Live Service integrations from both native and hybrid mobile apps, across any platform. Also, are you building web applications with ASP.NET but missing some zing? Telerik UI for ASP.NET provides a comprehensive toolset with 80+ controls and rich user experience for your every need. Plus, your web applications can now be sporting responsive and adaptive rendering techniques, making them work on any screen across various form factors. Give it a spin!

SamBasu
About the Author

Sam Basu

Sam Basu is a technologist, author, speaker, Microsoft MVP, gadget-lover and Progress Developer Advocate for Telerik products. With a long developer background, he now spends much of his time advocating modern web/mobile/cloud development platforms on Microsoft/Telerik technology stacks. His spare times call for travel, fast cars, cricket and culinary adventures with the family. You can find him on the internet.

Comments

Comments are disabled in preview mode.