09 December 2014 Microsoft Account, Auth, LiveSDK Robert Muehsig

In this blogpost I will take a deeper look at the LiveSDK to authenticate users by their Microsoft Accounts and display some profile information of the given user.

Didn’t ASP.NET Identity try to solve this problem?

If you only need the “Authentication”-Part, this might be true (here is one quick walkthrough). In theory you are only one checkbox away from the solution with the new Identity system.

But if you need deeper integration and want to retrieve data from OneDrive, OneNote or Outlook.com then you need to take a look at the LiveSDK. Maybe you can use the auth token from the ASP.NET Identity part and use this for the LiveSDK - but I’m not sure on this. Another point is that the ASP.NET Identity stuff feels so bloated and the database part is scary.

Our Mission: Pure LiveSDK, no magic.

Before you start: Setup the Domain and get the API Key & Secret

The setup flow is the same as for Twitter/Facebook/Google Auth, but with one (stupid) limitation.

First step: Create an App in the Microsoft Developer Center.

Second step: Enter the Root & Redirect Domain for the App. You will need a “real” URL - localhost is not accepted (d’oh).

Because real URLs are always kinda painful while developing you have two options:

  • a) Manipulate your hosts file (%SystemRoot%\system32\drivers\etc\hosts)
  • b) Use a service like localtest.me

I will stick to b) with the blogpostsample.localtest.me URL. To setup the binding I will also commit a Powershell file called “Enable-LocalTestMe.ps1” - this should ramp up everything on your development machine and make VS & IIS Express happy. After that you can F5 to your WebApp and it will open at “blogpostsample.localtest.me”. Yay!

So, my registration inside the DevCenter looks like this:

x

ASP.NET & LiveSDK

Next step: Create a new ASP.NET MVC app without any authentication provider and get the Live SDK for ASP.NET NuGet package.

The LiveSDK has two main parts:

  • LiveAuthClient: For the authentication part.
  • LiveConnectClient: After successful authentication interact with the service.

To learn more about the LiveSDK follow this MSDN link.

My sample code doesn’t store any token on the client or does any other clever mechanics and it even has hardcoded URLs in it, but this should work for the demo ;).

Trigger Authentication Flow

You need to list all “needed” scopes for the authentication flow. The scopes are documented here. The API uses OAuth2 for the authorization flow.

private static readonly string[] scopes =
    new string[] { 
        "wl.signin", 
        "wl.basic", 
        "wl.calendars" };

private readonly LiveAuthClient authClient;

public AuthController()
{
    authClient = new LiveAuthClient("0000000044121F5D", "b6lolb9jiF-zaMtp8KXcRNJ7ACz37SuK", "http://blogpostsample.localtest.me/Auth/Redirect");
}

public async Task<ActionResult> Index()
{
    LiveLoginResult loginStatus = await this.authClient.InitializeWebSessionAsync(HttpContext);
    switch (loginStatus.Status)
    {
        case LiveConnectSessionStatus.Expired:
        case LiveConnectSessionStatus.Unknown:
            string reAuthUrl = authClient.GetLoginUrl(scopes);
            return new RedirectResult(reAuthUrl);
    }

    return RedirectToAction("Index", "Home");
}

This code will initialize the authentication flow and create the “LiveAuthClient” and (hopefully) redirect the browser to the Microsoft Account Login.

x

On the first login the user needs to consent the desired “scopes”.

x

After this step the user will be redirected to the redirect url (in my case …/Auth/Redirect).

Get Microsoft Account Data

So, now this part is a bit magic, but I guess the “ExchangeAuthCodeAsync” will load the token from the Request and validate it. If everything is correct the status should be “Connected”.

public async Task<ActionResult> Redirect()
{
    var result = await authClient.ExchangeAuthCodeAsync(HttpContext);
    if (result.Status == LiveConnectSessionStatus.Connected)
    {
        var client = new LiveConnectClient(this.authClient.Session);
        LiveOperationResult meResult = await client.GetAsync("me");
        LiveOperationResult mePicResult = await client.GetAsync("me/picture");
        LiveOperationResult calendarResult = await client.GetAsync("me/calendars");

        ViewBag.Name = meResult.Result["name"].ToString();
        ViewBag.PhotoLocation = mePicResult.Result["location"].ToString();
        ViewBag.CalendarJson = calendarResult.RawResult;
    }

    return View();
}

The LiveConnectClient is a relatively thin layer on top of the REST API.

Result:

x

Mission accomplished!

The code so far was trivial, but will run (but maybe not in the most robust way).

If you want to learn more, the LiveSDK is on GitHub and the Interactive Live SDK might be useful for you.

The source code is available on our GitHub-Samples-Repo.

I also posted a short blogpost in German about Microsoft Account Authentication ASP.NET Identity some month ago.

Hope this helps!


Written by Robert Muehsig

Software Developer - from Dresden, Germany, now living & working in Switzerland. Microsoft MVP & Web Geek.
Other Projects: KnowYourStack.com | ExpensiveMeeting | EinKofferVollerReisen.de

If you like the content and want to support me you could buy me a beer or a coffee via Litecoin or Bitcoin - thanks for reading!