Sunday, September 09, 2012

Windows Azure Mobile Services Preview Walkthrough–Part 2: Authenticating Windows 8 App Users (C#)

Previous member of this series:

Part 2 of 5: imageThe Windows Azure Mobile Services (WAMoS) Preview’s initial release enables application developers targeting Windows 8 to automate the following programming tasks for Windows Store Apps:

  1. Creating a Windows Azure SQL Database (WASDB) instance and table to persist data entered in a Windows 8 Modern (formerly Metro) UI application’s form
  2. Connecting the table to the data entry front end app 
  3. Adding and authenticating the application’s users
  4. Pushing notifications to users

Later members of this series:


This walkthrough describes the process for completing task 3:

  1. Registering your Windows 8 app at the Live Connect Developer Center
  2. Restricting permissions to authenticated users
  3. Adding authentication code to the front-end application
  4. Authorizing users with scripts

The walkthrough is based on a combination of the Get started with authentication in Mobile Services and Authorize users with scripts tutorials. It has additional and updated screen captures for the first three operations. Step 4 is taken almost verbatim from the Microsoft tutorial.

A future walkthrough will cover task 4, Pushing notifications to users.

Prerequisites: Completion of the oakleaf-todo C# application in Part 1 and downloading/installing the Live SDK for Windows and Windows Phone, which provides a set of controls and APIs that enable applications to integrate single sign-on (SSO) with Microsoft accounts and access information from SkyDrive, Hotmail, and Windows Live Messenger on Windows Phone and Windows 8.


1 - Registering your Windows 8 app at the Live Connect Developer Center

Taking advantage of single sign-on with the user’s Microsoft account requires registering the Windows 8 app on the Live Connect Developer center's Push Notifications & Live Connect page from Visual Studio 2012:

1.1. Open the TodoList application in Visual Studio 2012 running under Windows 8, display Solution explorer, select the Package.appsmanifest node and click the Packaging tab:

1-1 PackageAppManifest

1-2. Make a note of the Package Display Name and Publisher values for registering your app, and navigate to the Windows Push Notifications & Live Connect page, log on with the Windows Live ID you used to create the app, and type the Package Display Name and Publisher values in the text boxes:

1-2 RegisterWithManifest

Note: The preceding screen capture has been edited to reduce white space but the obsolete capture from Video Studio has not been updated.

1-3. Click the I Accept button to configure the application manifest and generate Package Name, Client Secret and Package SID values:

1-3 AppRegistered

1-4. Copy the Package Name value to the clipboard, return to Visual Studio, and paste the Package Name value into the eponymous text box:

1-4 PackageNameInVS

1-5. Press Ctrl+s to save the value, log on to the Windows Azure Management Portal, click the Mobile Services icon in the navigation frame, click your app to open its management page and click the Dashboard button:

1-5 OakLeaf ToDo Dashboard

1-6. Make a note of the Site URL and navigate to the Live Connect Developer Center’s My Applications dashboard:

1-6 My Applications List

1-7. Click the app item (oakleaf_todo for this example) to display its details page:

1-7 OakLeaf Todo Details

1-8. Click the Edit Settings and API Settings buttons to open the Edit API Settings page and paste the Site URL value from step 5 in the Redirect Domain text box:

1-8 OakLeaf Todo Edit API Settings

1-9. Accept the remaining defaults and click the Save button to save your changes, return to the Management Portal, click the Identity button, and paste the Client Secret value in the text box:

1-9 Paste Client Secret to Identity

1-10. Click Save and Yes to save and confirm the change and complete configuration of your Mobile Service and client app for Live Connect.


2 – Restricting Permissions to Authenticated Users

2-1. Return to the Management Portal with your app selected, click the Data tab and select the ToDoItem table, which displays the persisted todo data:

2-1 todoitem Table Permissions

2-2. Click the Permissions tab to open the Table Permissions page and change all four permissions from the default Anybody with the Application Key to Only Authenticated Users:

image

2-3. Click Save to save the changed permissions, return to Visual Studio, press F5 to build and run the application, and click Save to attempt to add an empty todo item, which generates an untrapped HTTP 401 Unauthorized runtime error:

2-3 201 Unauthorized runtime error in VS

Note: The 201 Unauthorized exception proves that user authentication in the back end is operational.

2-4. Press Shift+F5 to close the application.


3 - Adding Authentication Code to the Front-End Application

3-1. After downloading and installing the Live SDK for Windows and Windows Phone, choose Project, Add Reference to open the Reference Manger dialog, select the Live SDK item and mark its check box:

3-1 Add Live SDK 5.0 reference in VS

3-2. Click OK to add the reference, open the mainpage.xaml.cs file and add the following two using statements at the top of the page:

using Microsoft.Live;
using Windows.UI.Popups;
3-2 Add Live SDK namespaces in VS

3-3. Add the following code at the end of the Main Page class to create a member variable for storing the current Live Connect session and a method to handle the authentication process:

private LiveConnectSession session;
private async System.Threading.Tasks.Task Authenticate()
{
    LiveAuthClient liveIdClient = new LiveAuthClient("<< INSERT REDIRECT DOMAIN HERE >>");


while (session == null)
{
    // Force a logout to make it easier to test with multiple Microsoft Accounts
    if (liveIdClient.CanLogout)
        liveIdClient.Logout();


    LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });
    if (result.Status == LiveConnectSessionStatus.Connected)
    {
        session = result.Session;
        LiveConnectClient client = new LiveConnectClient(result.Session);
        LiveOperationResult meResult = await client.GetAsync("me");
        MobileServiceUser loginResult = await App.MobileService.LoginAsync(result.Session.AuthenticationToken);


        string title = string.Format("Welcome {0}!", meResult.Result["first_name"]);
        var message = string.Format("You are now logged in - {0}", loginResult.UserId);
        var dialog = new MessageDialog(message, title);
        dialog.Commands.Add(new UICommand("OK"));
        await dialog.ShowAsync();
    }
    else
    {
        session = null;
        var dialog = new MessageDialog("You must log in.", "Login Required");
        dialog.Commands.Add(new UICommand("OK"));
        await dialog.ShowAsync();
    }
}
}

Note: The preceding code forces a logout, when possible, to make sure that the user is prompted for credentials each time the application runs. This makes it easier to test the application with different Microsoft Accounts to ensure that the authentication is working correctly. This mechanism will only work if the logged in user does not have a connected Microsoft account.

Replace the << INSERT REDIRECT DOMAIN HERE >> string from the previous step with the redirect domain that was specified when setting up the app in Live Connect, in the format https://service-name.azure-mobile.net/:

3-3 Add LiveConnectSession in VS

3-4. Replace the existing OnNavigatedTo event handler with the handler that calls the new Authenticate method:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    await Authenticate();
    RefreshTodoItems();
}
3-4 Add OnNavigatedTo handler in VS

3-5. Press the F5 key to run the app and request permission to use your current credentials:

3-5 Let this app access your info screen

3-6. Click yes to sign into Live Connect with your Microsoft Account and receive this welcome message:

3-6 Login welcome screen

3-7. Click OK to dismiss the popup message. At this point, you are authenticated and can add and query todo items.


4 - Authorizing Users with Scripts

The Todo sample app reads and inserts data, so you must register scripts for these operations against the TodoItem table.

4-1. Log on to the Windows Azure Management Portal, click the Mobile Services node in the navigation pane, and click your app.

4-1 oakleaf-todo page

4-2 Click the Data tab and click the TodoItem table:

4-2 ToDoItem table

4-3. Click the Script tab and accept the default Insert operation:

4-3 Insert Script Default

4-4. Replace the default script with the following function:

function insert(item, user, request) {
  item.userId = user.userId;    
  request.execute();
}

4-4 Modified Insert Script

This script adds a userId value to the item, which is the user ID of the authenticated user, before it is inserted into the TodoItem table.

Note: Dynamic Schema must be enabled the first time that this insert script runs. With dynamic schema enabled, Mobile Services automatically adds the userId column to the TodoItem table on the first execution. Dynamic schema is enabled by default for a new mobile service, and it should be disabled before the app is published to the Windows Store.

4-5. Click save and repeat steps 4-3 and 4-4 to replace the existing Read operation with the following function:

function read(query, user, request) {
   query.where({ userId: user.userId });    
   request.execute();
}
4-5 Modified Read Script

This script filters the returned TodoItem objects so that each user only receives the items that they inserted.

4-6. Click Save to save the changes to the Read function.

Test the app

4-7. In Visual Studio 2012 Express or higher, open the project that you modified earlier in this walkthrough.

4-8. Press the F5 key to build and run the app, sign into Live Connect with your Live ID or click OK to acknowledge the Welcome page, and click the Refresh button:

4-7 Empty Data Entry Page

Notice that this time, although there are items already in the TodoItem table from preview tutorials, no items are returned. This happens because previous items were inserted without the userId column and now have null userId values.

4-9. In the app, enter text in the Insert a TodoItem text box and click Save.

image

This inserts both the text and the userId in the TodoItem table in the mobile service. Because the new item has the correct userId value, it is returned by the mobile service and displayed in the second column.

4-10. Back in the todoitem table in the Management Portal, click Browse and verify that the newly added item how has an associated userId value:

4-9 todoitem table browsed

4-11. (Optional) If you have an additional Live ID, you can verify that users can only see their own data by closing the app (Alt+F4), logging out of your current Live ID and then running it again. When the login credentials dialog is displayed, enter a different Microsoft account, and then verify that the items entered under the previous account are not displayed.


0 comments: