Windows Azure Mobile Services Preview Walkthrough–Part 2: Authenticating Windows 8 App Users (C#)
Previous member of this series:
- Windows Azure Mobile Services Preview Walkthrough–Part 1: Windows 8 ToDo Demo Application (C#) - 9/8/2012, updated 12/28/2012 covered tasks 1 and 2.
Part 2 of 5: The 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:
- 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
- Connecting the table to the data entry front end app
- Adding and authenticating the application’s users
- Pushing notifications to users
Later members of this series:
- Windows Azure Mobile Services Preview Walkthrough–Part 3: Pushing Notifications to Windows 8 Users (C#) 9/22/2012
- Windows Azure Mobile Services Preview Walkthrough–Part 4: Customizing the UI for the Windows Store of 9/15/2012
- Windows Azure Mobile Services Preview Walkthrough–Part 5: Distributing Your App From the Windows Store updated 9/19/2012
This walkthrough describes the process for completing task 3:
- Registering your Windows 8 app at the Live Connect Developer Center
- Restricting permissions to authenticated users
- Adding authentication code to the front-end application
- 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-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:
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-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-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-6. Make a note of the Site URL and navigate to the Live Connect Developer Center’s My Applications dashboard:
1-7. Click the app item (oakleaf_todo for this example) to display its details page:
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-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-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-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:
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:
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-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-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-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-5. Press the F5 key to run the app and request permission to use your current credentials:
3-6. Click yes to sign into Live Connect with your Microsoft Account and receive this welcome message:
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-2 Click the Data tab and click the TodoItem table:
4-3. Click the Script tab and accept the default Insert operation:
4-4. Replace the default script with the following function:
function insert(item, user, request) { item.userId = user.userId; request.execute(); }
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(); }
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:
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.
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-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:
Post a Comment