Using Windows Live ID in a WP7 App

You might be surprised to learn that despite the close integration of Windows Live ID and Windows Phone there is no way to make use of the existing Windows Live ID credentials within a third party application. This means that if you want to access the user’s Windows Live profile, their list of contacts or any other data that is available via the new Messenger Connect API you will have to get the user to authenticate against Windows Live ID from within your application. In this post you’ll learn how to work with the Messenger Connect APIs for authenticate from within a Windows Phone application.

Updated Terms of Use for Mobile Applications

The Windows Live Developer Services – Terms of Use was updated June 2011 to permit the use within mobile applications (see section 2). However, it’s important to note that the agreement states that “Developing or distributing applications for mobile devices that use Version 3 or Version 4 of the Windows Live API … is not authorized”. This means that you can’t use the old Web or Delegated authentication, you now need to use the Messenger Connect implementation of OAuth 2.

Step 1: Creating a Windows Live Application

Open a web browser and go to the Windows Live Developer Portal. You’ll need to sign in with a Windows Live ID. As you sign in there is a notice which states that if there are going to be multiple developers working on the application you should create a company Live ID to which the application can be registered. Important: There is no way to transfer an application from one Live ID to another. This means that if you create an application with a personal Live ID account it will not be possible to transfer it to another Live ID should you leave the company, or wish to sell the rights to the application. My recommendation would be to take a moment and think about the strategy that works for you. You may decide to use your Live ID, a company Live ID or even create a Live ID that is specific to the application. The last option is most suited for an application you may wish to sell in the future.

Once you’ve signed in, click on the My Apps tab and then on the Create application link. This will prompt you for an application name and language of the application as seen in Figure 1.

WP7 Auth Figure 1

Figure 1

Once you click the “I accept” button you’ll be allocated a Client ID and Client secret as shown in Figure 2.

WP7 Auth Figure 2

Figure 2

At this point you should navigate back to the Application Settings Page and add as much information about the application as you can (icon, description etc). When the user goes to authenticate using Windows Live ID within your Windows Phone application they will be informed as to what Windows Live application is requesting them to authenticate. This will include the information you’ve entered into the Application Settings Page – the more accurate and informative, the more likely the user will agree to authenticate using Windows Live ID.

Step 2: Creating the Shell WP7 App

We’ll start with a very basic application consisting of a Button, to initiate the authentication process, a WebBrowser control, into which the user will enter their credentials to authenticate against Windows Live, and lastly a couple of TextBlock elements to display information about the authenticated user.

<phone:PhoneApplicationPage x:Class="WindowsLiveIdSampleApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone">
    <Grid>
        <StackPanel x:Name="LayoutRoot" Background="Transparent">
            <Button Content="Authenticate" Click="AuthenticateClick" />
            <TextBlock x:Name="UserNameText" />
            <TextBlock x:Name="UserIdText" />
        </StackPanel>
        <phone:WebBrowser x:Name="AuthenticationBrowser" Visibility="Collapsed" Navigated="BrowserNavigated" IsScriptEnabled="True" />
    </Grid>
</phone:PhoneApplicationPage>

Step 3: Create the Login URL

In essence the purpose of OAuth is to delegate the responsibility of authenticating the user to the Windows Live service. This includes the capture of username and password information – the host application should never come in direct contact with or attempt to cache this information. To achieve this in a Windows Phone application you need to navigate a WebBrowser control to the appropriate page for the user to login and authorise the host application.

This step involves building the correct URL to navigate the WebBrowser control to. The URL consists of a number of elements:

  • Base URL: https://oauth.live.com/authorize
  • Query String Parameters:
    • Client ID: The Client ID of your Windows Live Application created earlier
    • Response Type: The type of authentication to use (we’re going to use “token”)
    • Scope: The parts of the users account the host application is requesting access to
    • Redirect URL: The URL that the browser will redirect to after authentication has been completed. For web applications this would be a page within your web site which will pick up the access token. However, because we’re building a client application you need to specify https://oauth.live.com/desktop which is a dedicated page provided for the purpose of extracting the access token.
    • Display: Determines how the login prompt will be styled. Use “touch” in order to get the most usable interface for a touch driven device.

The only trick to this step is making sure that all the parameters are correctly concatenated and appropriately URL encoded.

var uriParams = new Dictionary<string, string>() {
    {"client_id", "<your_client_id>"},
    {"response_type", "token"},
    {"scope", "wl.signin,wl.basic,wl.offline_access"},
    {"redirect_uri", "https://oauth.live.com/desktop"},
    {"display", "touch"}
};

StringBuilder urlBuilder = new StringBuilder();
foreach (var current in uriParams) {
  if (urlBuilder.Length>0) {
      urlBuilder.Append("&");
  }
  var encoded = HttpUtility.UrlEncode(current.Value);
  urlBuilder.AppendFormat("{0}={1}", current.Key, encoded);
}
var loginUrl= "https://oauth.live.com/authorize?" + urlBuilder.ToString();

In this case the scope we’ve specified requests permission for the application to authenticate (wl.signin), access profile information (wl.basic) and persist the access token (wl.offline_access). Don’t forget to replace (including the angled brackets) with your Client ID that you got when you created the Windows Live Application in Step 1.

Step 4: Prompt Windows Live ID Login

To get the user to login, all you have to do is to navigate the WebBrowser control to the loginUrl you just created. In the case of the application you’ll also need to display the WebBrowser control.

AuthenticationBrowser.Navigate(new Uri(loginUrl));
AuthenticationBrowser.Visibility = Visibility.Visible;

Step 5: User Logs In and Approves the Application

The user will see a number of screens which will prompt them to enter their credentials and then grant the requested permissions to the application, as seen in Figure 3.

WP7 Auth Figure 3

Figure 3

Step 6: Extract the Access Token

In Figure 3, the final image is of a blank page. This is actually the redirect URI, i.e. https://oauth.live.com/desktop which should never be shown. Instead your application should parse the URI query string for this page and extract the access token, before hiding the WebBrowser control.

public string AccessToken { get; set; }
private void BrowserNavigated(object sender, NavigationEventArgs e) {
  if (e.Uri.AbsoluteUri.ToLower().Contains("https://oauth.live.com/desktop")) {
    string text = HttpUtility.HtmlDecode(e.Uri.Fragment).TrimStart('#');
    var pairs = text.Split('&');
    foreach (var pair in pairs) {
      var kvp = pair.Split('=');
      if (kvp.Length == 2) {
        if (kvp[0] == "access_token") {
          AccessToken = kvp[1];
          MessageBox.Show("Access granted");
        }
      }
    }

    if (string.IsNullOrEmpty(AccessToken)) {
        MessageBox.Show("Unable to authenticate");
    }

    AuthenticationBrowser.Visibility = System.Windows.Visibility.Collapsed;
  }
} 

Step 7: Accessing Content from Windows Live

Whilst having the Access Token verifies that the user is a legitimate Windows Live ID user it shouldn’t be used to uniquely identify the user. To get information about the signed in user you need to make one more request, this time to the Messenger Connect API itself. All requests to the Messenger Connect APIs (v5) start with the base URL of https://apis.live.net/v5.0 and in the case of requesting the user’s profile you simply have to append /me. Make a request to this URL, specifying the Access Token in the query string and you’ll get back a JSON string that represents the current logged in user. The following code illustrates this using the HttpWebRequest class.

private void RequestUserProfile() {
    var profileUrl = string.Format("https://apis.live.net/v5.0/me?access_token={0}", HttpUtility.UrlEncode(AccessToken));

    var request = HttpWebRequest.Create(new Uri(profileUrl));
    request.Method = "GET";
    request.BeginGetResponse(result => {
        try {
            var resp = (result.AsyncState as HttpWebRequest).EndGetResponse(result);
            using (var strm = resp.GetResponseStream()) {
                var serializer = new DataContractJsonSerializer(typeof (WindowsLiveProfile));
                var profile = serializer.ReadObject(strm) as WindowsLiveProfile;
                this.Dispatcher.BeginInvoke((Action<WindowsLiveProfile>) ((user) => {
                    this.UserIdText.Text = user.Id;
                    this.UserNameText.Text = user.Name;
                }), profile);
            }
        }
        catch (Exception ex) {
            this.Dispatcher.BeginInvoke( () => 
            MessageBox.Show("Unable to attain profile information"));
        }
    }, request);
}

[DataContract]
public class WindowsLiveProfile {
    [DataMember(Name="id")]
    public string Id { get; set; }
    [DataMember(Name="name")]
    public string Name { get; set; }
}

The final output is the user’s name and ID appearing in the relevant TextBlock controls as seen in Figure 4.

WP7 Auth Figure 4

Figure 4

In this post you’ve seen how to authenticate against Windows Live and use the Messenger Connect APIs to retrieve information about the current user. There are other aspects of the users profile you can request access too, such contacts, events, email and even the ability to add to the user’s activity feed and update their status. These can all be accessed by specifying the appropriate scope and then accessing the corresponding Messenger Connect API path. More information is available via the Windows Live Developer Portal and the Messenger Connect documentation.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • John

    I must be missing something or you left a step of two out. If I follow through just step 6 it won’t authenticate me. The error on the webpage is “The provided request must include a ‘client_id’ parameter”.

    Looking at th URL I wonder if something is out of order in the code as it looks like this:

    …?[client_id, XXXXXXXX]=XXXXXXXX&[response_type,token]=token$….

    Also, to complete the last steps do I need to add a reference to an assembly? it doesn’t like DataContractJsonSerializer even if I add a using System.Runtime.Serializtion.

  • http://www.builttoroam.com Nick

    Hi John

    Thanks for spotting a minor issue with the code in Step 3. The AppendFormat method call should take current.Key as the second parameter instead of just current.

    With regards to the DataContractJsonSerializer you will need to add a reference to System.ServiceModel.Web and then “using System.Runtime.Serialization.Json;”. Don’t ask me why it’s in that assembly….

  • gaurav

    Hello Nick,

    Good article.
    One question though even if you set scope to “wl.offline_access”, the access token expires after 3600 seconds (or 1hour).
    So, do you need to get consent again after every hour?

    Thanks.

  • http://www.builttoroam.com Nick
  • khalid

    Is there a way to autheitcate the user using a windows phone FORM and in some way pass these info to the API? because using a browser is not beautiful.
    thank you

  • http://nicksnettravels.builttoroam.com Nick

    Khalid, there is no way to authenticate using a WP form – this goes against the principle (flawed as it may be) of OAuth.

  • Ananth

    Thanks for the tutorial, it worked great!

  • Alex

    Thanks for the tutorial, it worked like a charm. I tried all day to make this work and thanks to you i finally managed.