Integrating Sharepoint And Windows Phone 7 Using Forms Based Authentication

Total Page:16

File Type:pdf, Size:1020Kb

Integrating Sharepoint And Windows Phone 7 Using Forms Based Authentication

1.

2.

Hands-On Lab Integrating SharePoint and Windows Phone 7 using Forms Based Authentication

Lab version: 1.0.0 Last updated: 11/14/2017

3. 4. 5.

6.

7.

Page | 1 CONTENTS 8.

Page | 2 Overview

9. Windows Phone 7 applications can use Forms-Based Authentication (FBA) to work with secured SharePoint resources. SharePoint 2010 includes an Authentication Web Service that can be used to authenticate requests using FBA. This lab will focus on using FBA to access secured SharePoint resources.

Objectives 1. In this hands-on lab, you will learn how to access SharePoint resources from a Windows Phone 7 application using FBA. Learn how to authenticate to SharePoint using the SharePoint Authentication Web service from a Windows Phone 7 application. Learn how to attach a FedAuth cookie to web requests to access secured SharePoint resources. Learn how to handled successful and failed authentication attempts.

Prerequisites 1. The following is required to complete this hands-on lab:

2. Note: See Setting Up A SharePoint and Windows Phone 7 Development Environment Module for instructions that describe how to set up the SharePoint and Windows Phone 7 developer machine.

3. Windows 7 x64 installed with all Windows Updates installed, in one of the following scenarios. Installed on a physical machine Installed on a bootable VHD  SharePoint 2010 installed on the Windows 7 x64 developer machine configured with a site collection that uses Forms Based Authentication (FBA). Windows Phone 7 Developer Tools http://download.microsoft.com/download/1/7/7/177D6AF8-17FA-40E7-AB53- 00B7CED31729/vm_web.exe Windows Phone 7 Developer Tools - January 2011 Update http://download.microsoft.com/download/6/D/6/6D66958D-891B-4C0E-BC32- 2DFC41917B11/WindowsPhoneDeveloperResources_en-US_Patch1.msp

Page | 3 Windows Phone Developer Tools Fix http://download.microsoft.com/download/6/D/6/6D66958D-891B-4C0E-BC32- 2DFC41917B11/VS10-KB2486994-x86.exe

4. Note: The following prerequisites are not included in the Setting Up A SharePoint and Windows Phone 7 Development Environment Module installation instructions. If you are using a development machine built according to the Setting Up A SharePoint and Windows Phone 7 Development Environment Module instructions you must install these components.

5. KB981002- WCF: Hotfix rollup in .NET 3.5 SP1 for Win 7 and Win 2k8 R2 http://code.msdn.microsoft.com/KB981002

Exercise 1: Creating a SharePoint List Data Source

1. In this exercise, you will deploy a list template to SharePoint and make a list based upon the template. The list template defines a list used to display important maintenance announcements. In this scenario, the Windows Phone 7 application will read and write to the announcement list and authenticate with the Authentication Web service. The Windows Phone 7 application allows users to view current maintenance announcements on their Windows Phone 7 device. Users with write permissions will be able to add announcements to the list as needed.

Note: If you have already created the Maintenance Announcements list in a previous lab you may skip to Exercise 2.

2. Task 1 – Deploying the List Template to a SharePoint Site In this task, you will deploy the maintenance announcements list template to a SharePoint site. The list template contains sample data used in the lab. 3. Open Internet Explorer and navigate to the SharePoint Team Site configured for Forms Based Authentication. 3.a. example: http://fbawp7 4. Log into the site using site collection administrator credentials. 5. Click Site Actions, and select Site Settings.

Page | 4 6. In the Galleries section, click List templates. 7. In the Ribbon, click the Documents tab. 8. Click Upload Document. 9. Click Browse… 10. Browse to the Maintenance Announcements.stp file located at %TrainingKitPath %\Labs\IntegratingFormsBasedAuthentication\Source\Before and select it. 11. Click Open. 12. Click OK. 13. Click Save. Verify the Maintenance Announcements list template appears in the List Templates Gallery.

13.a.

13.b. Figure 1 13.c. List Template Gallery

13.d.

Task 2 – Creating the Maintenance Announcement List In this task, you will use the maintenance announcements list template to create the maintenance announcements list. 1. Open Internet Explorer and navigate to the SharePoint Team Site configured for Forms Based Authentication. 1.a. example: http://fbawp7 2. Log into the site using site collection administrator credentials. 3. Click Site Actions and select More Options. 4. In the Filter By section, select List.

Page | 5 5. Select the Maintenance Announcements list.

1.b. 1.c. Figure 2 1.d. Selecting the Maintenance Announcements template

1.e. 6. In the Name textbox enter Maintenance Announcements. 7. Click Create. 8. Verify the Maintenance Announcements list contains the following sample data.

1.f.

1.g. Figure 3 1.h. Maintenance Announcements list with content

Page | 6 Exercise 2: Creating the Windows Phone 7 Application

1. In this exercise, you will complete a Windows Phone 7 application that can read and write to the maintenance announcements SharePoint list created in exercise 1. This exercise focuses on the steps to authenticate to SharePoint using forms based authentication. Task 1 – Beginning the Exercise 2. In this task, you will open the lab solution in Visual Studio 2010. 3. Make sure that you have downloaded and installed the items listed in System Requirements above prior to beginning this exercise. 4. Launch Visual Studio 2010 as administrator and open the lab project by selecting File » Open » Project. 4.a. Browse to the WP7.Security.FBA.sln file located at %TrainingKitPath %\Labs\IntegratingFormsBasedAuthentication\Source\Before and select it. 4.b. Click Open to open the solution.

Task 2 – Configuring Constants in the Windows Phone 7 Application 1. In this task, you will configure the constants used in the Windows Phone 7 application to work with your development environment. 1. In the WP7.Security.FBA, in the Utilities folder, open the Constants.cs file. 2. Change the value for the USER_NAME and USER_PASSWORD constants to represent a Forms Based Authentication user specific to your development environment. For this lab, the user requires read and write permissions. 3. Change the value for the AUTHENTICATION_SERVICE_URL constant to the URL specific to your development environment. The following code example demonstrates the value for a SharePoint server named fbawp7. 1.a. C# 1.b. public const string AUTHENTICATION_SERVICE_URL = "http://fbawp7/_vti_bin/authentication.asmx";

1.c. 1.d. The SharePoint Authentication.asmx web service allows a remote device to authenticate to SharePoint using forms-based authentication.

Page | 7 Task 3 – Adding the FBAAuthenticatedEventArgs Class to the Project 1. In this task, you will add the FBAAuthenticatedEventArgs to the Utils.cs File. 2. In the WP7.Security.FBA, in the Utilities folder, open the Utils.cs file. 3. Add the following code under the //TODO: 6.1.1 comment to define the FBAAuthenticatedEventArgs class: 3.a. C# 3.b. public class FBAAuthenticatedEventArgs : EventArgs 3.c. { 3.d. public CookieContainer CookieJar { get; private set; } 3.e. 3.f. public FBAAuthenticatedEventArgs(CookieContainer c) 3.g. { 3.h. CookieJar = c; 3.i. } 3.j. }

3.k. 3.l. The FBAAuthenticatedEventArgs class inherits EventArgs. This class is used to pass the CookieContainer to the caller after the call has been authenticated. The CookieContainer will contain the HttpOnly FedAuth cookie with the authentication information.

Task 4 – Modifying the FBAAuthorization Class to Authenticate Using the SharePoint Authentication.asmx Web Service 1. In this task, you will modify the ServiceReferences.ClientConfig file to support the CookieContainer used with Forms BasedAuthentication. The code used to authenticate to the SharePoint server in this lab uses Forms Based Authentication. Forms Based Authentication requires the use of a CookieContainer. Please see the Security With SharePoint And Windows Phone 7 Applications Module slide deck for more information about Forms Based Authentication. 1. In the WP7.Security.FBA, in the Utilities folder, open the Utils.cs file. 2. Add the following code under the //TODO: 6.1.2 comment to define the FBAAuthenticatedEventArgs class: 2.a. C# 2.b. public event EventHandler OnAuthenticated; 2.c. public event EventHandler OnFailedAuthentication;

Page | 8 2.d. 2.e. The above code defines the OnAuthenticated and OnFailedAuthentication events for the FBAAuthorization class. The FBAAuthorization class contains the code to authenticate to SharePoint using the Authentication.asmx web service. Clients will bind to the FBAAuthorization instance’s OnAuthenticated event to receive notification that the authentication is completed. This event passes the CookieContainer containing the authentication cookie to the caller using an instance of the FBAAuthenticatedEventArgs class. Clients can bind to the OnFailedAuthentication event to be notified of failed authentication attempts. 3. Add the following code under the //TODO: 6.1.3 comment to define the FBAAuthorization constructor: 3.a. C# 3.b. public FBAAuthorization(string UserName, string UserPassword, string AuthenticationServiceURL) 3.c. { 3.d. this.UserName = UserName; 3.e. this.UserPassword = UserPassword; 3.f. this.AuthenticationServiceURL = AuthenticationServiceURL; 3.g. }

3.h. 3.i. The above code defines the FBAAuthorization class’s constructor. The constructor simply stores the passed in parameters into properties for later use. 4. Add the following code under the //TODO: 6.1.4 comment to define the Authenticate method: 4.a. C# 4.b. public void Authenticate() 4.c. { 4.d. System.Uri authServiceUri = new Uri(AuthenticationServiceURL); 4.e. HttpWebRequest spAuthReq = HttpWebRequest.Create(authServiceUri) as HttpWebRequest; 4.f. spAuthReq.CookieContainer = cookieJar; 4.g. spAuthReq.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/Login"; 4.h. spAuthReq.ContentType = "text/xml; charset=utf-8"; 4.i. spAuthReq.Method = "POST";

Page | 9 4.j. spAuthReq.BeginGetRequestStream(new AsyncCallback(spAuthReqCallBack), spAuthReq); 4.k. }

4.l. 4.m. The above code creates an HttpWebRequest object using the stored Url to the SharePoint authentication service. The key to this method is to attach an existing CookieContainer object (cookieJar) to the request. This allows the code to easily access the CookieContainer in the return method. The call to Authentication.asmx web services posts a SOAP payload. This method defines the BeginGetRequestStream callback method in the call to BeginGetRequestStream. 5. Add the following code under the //TODO: 6.1.5 comment to define the spAuthReqCallBack method: 5.a. C# 5.b. private void spAuthReqCallBack(IAsyncResult asyncResult) 5.c. { 5.d. string envelope = 5.e. @" 5.f. 5.g. 5.h. 5.i. {0} 5.j. {1} 5.k. 5.l. 5.m. "; 5.n. 5.o. UTF8Encoding encoding = new UTF8Encoding(); 5.p. HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; 5.q. Stream _body = request.EndGetRequestStream(asyncResult); 5.r. envelope = string.Format(envelope, UserName, UserPassword); 5.s. byte[] formBytes = encoding.GetBytes(envelope); 5.t. 5.u. _body.Write(formBytes, 0, formBytes.Length);

Page | 10 5.v. _body.Close(); 5.w. 5.x. request.BeginGetResponse(new AsyncCallback(ResponseCallback), request); 5.y. }

5.z. 5.aa. The above code defines the XML SOAP payload for the authentication request. The envelope variable contains the basic SOAP request. The username and password values are set using the stored values in the FBAAuthorization class. The HttpWebRequest instance defines the callback in the BeginGetResponse call. The BeginGetResponse starts the asynchronous service request. When completed the code will call the ResponseCallback method. 6. Add the following code under the //TODO: 6.1.6 comment to define the ResponseCallback method: 6.a. C# 6.b. private void ResponseCallback(IAsyncResult asyncResult) 6.c. { 6.d. string responseString = ""; 6.e. 6.f. HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; 6.g. HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); 6.h. Stream content = response.GetResponseStream(); 6.i. 6.j. if (request != null && response != null) 6.k. { 6.l. if (response.StatusCode == HttpStatusCode.OK) 6.m. { 6.n. using (StreamReader reader = new StreamReader(content)) 6.o. { 6.p. responseString = reader.ReadToEnd(); 6.q. reader.Close(); 6.r. } 6.s. } 6.t. }

Page | 11 6.u. 6.v. if (responseString.Contains("NoError")) 6.w. { 6.x. EventHandler authenticated = OnAuthenticated; 6.y. if (authenticated != null) 6.z. { 6.aa. authenticated(this, new FBAAuthenticatedEventArgs(cookieJar)); 6.ab. } 6.ac. } 6.ad. else 6.ae. { 6.af. EventHandler failedAuth = OnFailedAuthentication; 6.ag. if (failedAuth != null) 6.ah. { 6.ai. failedAuth(this, null); 6.aj. } 6.ak. } 6.al. }

6.am. The above code is called when the authentication request returns. This code retrieves the SOAP response from the HttpWebResponse object. The SOAP response is an XML string. This example simply looks for “NoError” in the string. The value of “NoError” means the login attempt was successful. Not finding the value of “NoError” indicates a failed login attempt. The code above raises the appropriate event, which is handled by the caller. The OnAuthenticated event returns an FBAAuthenticatedEventArgs object to the event listener. The FBAAuthenticatedEventArgs has a reference to the returned CookieContainer that was populated with the HttpOnly FedAuth cookie. The HttpOnly cookie cannot be seen or manipulated using code in the current version of the phone platform. Because the FedAuth cookie is marked as HttpOnly the CookieContainer must be passed back instead of an individual cookie.

Task 5 – Creating a Static Variable to Store the CookieContainer 1. In this task, you will create a global, static variable to store the CookieContainer. The CookieConainer containing the FBA cookie will be needed by any class calling authenticated resources from SharePoint.

Page | 12 2. In the WP7.Security.FBA, right-click App.xaml, and select View Code. 2. Add the following code under the //TODO: 6.1.7 comment to define the CookieJar property: 2.a. C# 2.b. public static CookieContainer CookieJar 2.c. { get; set; }

2.d. 2.e. The above code creates a static, global property called CookieJar. This property stores the CookieContainer object returned from the authentication call for use in accessing secured resources from SharePoint.

Task 6 – Completing the ViewModel to Authenticate Using FBA 1. In this task, you will use the complete the existing MainViewModel class to include authentication calls to the FBAAuthorization instance. 2. In the WP7.Security.FBA, in the ViewModels folder, open the MainViewModel.cs file. 3. Add the following code under the //TODO: 6.1.8 comment to define the class-level FBAAuthorization variable: 3.a. C# 3.b. FBAAuthorization Auth;

3.c. 3.d. The Auth variable will contain a reference to an FBAAuthorization object created in the class constructor. 4. Add the following code under the //TODO: 6.1.9 comment to define the class-level Auth_OnAuthenticated and Auth_OnFailedAuthentication event handlers: 4.a. C# 4.b. void Auth_OnAuthenticated(object sender, FBAAuthenticatedEventArgs e) 4.c. { 4.d. App.CookieJar = e.CookieJar; 4.e. LoadAnnouncements(); 4.f. } 4.g. 4.h. void Auth_OnFailedAuthentication(object sender, EventArgs e) 4.i. { 4.j. Deployment.Current.Dispatcher.BeginInvoke(() => 4.k. MessageBox.Show("Failed Login Attempt")

Page | 13 4.l. ); 4.m. }

4.n. 4.o. The Auth_OnAuthenticated event handler is bound to the Auth variable in the class and contain a reference to the FBAAuthorization object created in the class constructor. This method is called when authorization is complete. The event handler stores the CookieContainer containing the FedAuth cookie in the static property CookieJar allowing the CookieContainer to be available to other objects in the project. Finally, the code calls LoadAnnouncements method. The LoadAnnouncements method starts the data retrieval process from SharePoint. 4.p. The Auth_OnFailedAuthentication event handler is also bound to the Auth variable. This event handler is called when the authentication service returns a failed authentication attempt. 5. Add the following code under the //TODO: 6.1.10 comment to define the MainViewModel constructor: 5.a. C# 5.b. public MainViewModel() 5.c. { 5.d. Auth = new FBAAuthorization(Constants.USER_NAME, Constants.USER_PASSWORD, Constants.AUTHENTICATION_SERVICE_URL); 5.e. Auth.OnAuthenticated += new EventHandler(Auth_OnAuthenticated); 5.f. Auth.OnFailedAuthentication += new EventHandler(Auth_OnFailedAuthentication); 5.g. }

5.h. 5.i. The MainViewModel constructor creates an instance of the FBAAuthorization class and sets the Auth variable to point to the new FBAAuthorization class. The constructor then defines the event handlers for the OnAuthenticated and OnFailedAuthentication events. 6. Add the following code under the //TODO: 6.1.11 comment attach the CookieContainer to the web service call: 6.a. C# 6.b. lists.CookieContainer = App.CookieJar;

6.c.

Page | 14 6.d. Once the CookieContainer with the FedAuth cookie is available secured SharePoint resources can be called by attaching the CookieContainer (located in App.CookieJar) to the request object. For a Web service accessed using a Visual Studio proxy object, the CookieContainer can be attached using the above code. Once the CookieContainer is attached to the request object, SharePoint will allow authorized access to secured resources based on the FedAuth cookie information. Each new request object will require the CookieContainer with the FBA cookie to be attached to the request object.

Exercise 3: Testing the Windows Phone 7 Application

1. In this exercise, you will test the Windows Phone 7 application. Task 1 – Testing the Application’ Authorization Functionality in Windows Phone 7 Emulator 2. In this task, you will test the Windows Phone 7 application using the Windows Phone 7 emulator. 1. In the WP7.Security.FBA solution, select Windows Phone 7 Emulator in the deployment location dropdown list. 2. In the WP7.Security.FBA solution, press F5. 3. The Windows Phone application starts in the emulator and displays the items from the Maintenance Announcements SharePoint list.

Page | 15 2.a. 2.b. Figure 4 2.c. Application displaying announcements from the SharePoint list

2.d. 4. Click on one of the maintenance announcements in the list to select it.

Page | 16 5. The Windows Phone application displays the details for the selected maintenance announcement from the SharePoint list.

2.e. 2.f. Figure 5 2.g. Application displaying announcement details

Page | 17 2.h. 6. Click the emulator’s back button to return to the list of announcements. 7. In the WP7.Security.FBA in Visual Studio press Shift-F5 to stop debugging.

Task 2 -Testing the Application’s Failed Authorization Functionality in Windows Phone 7 Emulator 1. In this task, you will test the Windows Phone 7 application with an incorrect user name. 1. In the WP7.Security.FBA project, in the Utilities folder, open the Constants.cs file. 2. Change the value for the USER_NAME to a username that does not have permissions on the SharePoint web site. For this task the user name does not have to exist on the server or in SharePoint. 3. In the WP7.Security.FBA solution, press F5. 8. The Windows Phone application starts in the emulator and displays the failed log in message.

Page | 18 1.a. 1.b. Figure 6 1.c. Application displaying failed login message

Summary

Page | 19 1. In this hands-on lab, you saw how to use the SharePoint Authentication Web service to authenticate to SharePoint using FBA. You also learned how to store and attach the CookieContainer containing the FedAuth cookie to a Web request to access secured SharePoint resources. Finally, you learned how to handle successful and failed authentication attempts.

Page | 20

Recommended publications