99
Hands-On Lab Web Services and Identity in Windows Azure Lab version: 2.0.0 Last updated: 4/8/2022

az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Hands-On LabWeb Services and Identity in Windows AzureLab version: 2.0.0

Last updated: 5/18/2023

Page 2: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

CONTENTS

OVERVIEW................................................................................................................................................. 3

GETTING STARTED: SETTING UP THE CERTIFICATES AND LOCAL STS..........................................7Task 1 - Generating the Required Certificates.....................................................................................7

Task 2 - Creating the local STS.............................................................................................................9

EXERCISE 1: USING WINDOWS IDENTITY FOUNDATION WITH A WCF SERVICE IN WINDOWS AZURE...................................................................................................................................................... 13

Task 1 – Implementing the Weather Service.....................................................................................14

Task 2 – Establishing a Trust Relationship between the WCF Service and the Development STS......21

Task 3 – Adding the Certificates to the Relying Party........................................................................27

Task 4 – Configuring the WCF Service HTTPS Endpoint.....................................................................30

Verification........................................................................................................................................35

EXERCISE 2: ADDING DIAGNOSTICS AND LOAD BALANCING.........................................................40Task 1 – Adding Diagnostics Support.................................................................................................40

Verification........................................................................................................................................47

Task 2 – Adding Load Balancing Support to the WCF Service............................................................50

Verification........................................................................................................................................59

EXERCISE 3: DEPLOYING THE WCF SERVICE TO WINDOWS AZURE..............................................61Task 1 – Creating the Hosted Service using the Windows Azure Management Portal......................62

Task 2 – Creating the Storage Account using the Windows Azure Management Portal....................68

Task 3 – Configuring the Web Role for Azure Deployment................................................................70

Task 4 – Uploading the Certificate and Staging Deployment to Windows Azure...............................75

Verification........................................................................................................................................81

SUMMARY................................................................................................................................................ 83

Page 3: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Overview

Windows Identity Foundation can simplify access to your Windows Communication Foundation (WCF) services, by providing the usual claims-based identity arsenal of good practices: authentication externalization, location independence, decoupling from credential types and many others. There is no reason for you not to enjoy the same advantages when you host your WCF services in Windows Azure: there are few practicalities that are intrinsic to the hosting platform, but the steps you need to follow are largely the same whether you are deploying your services on-premises or in the cloud. If you want to be fully aware of the differences between the two cases, you can optionally go through the lab “Web Services and Identity” and learn about how to use WCF and WIF on-premises before starting the current lab: please note that it is entirely optional, as this HOL is self-contained and independent.

This lab is a step by step guide that will help you to use claims-based identity for handling authentication and access management for your WCF services hosted in Windows Azure; it will show you how you can still take advantage of local identities for authenticating your users, despite the fact that your services are now hosted in the cloud. The lab will walk you through all the practicalities of taking advantage of the unique characteristics of the Windows Azure environment from your Windows Identity Foundation settings.

More precisely, you will learn how to:

Use Windows Identity Foundation with WCF services hosted in Windows Azure

Trusting an on-premise STS from a WCF service hosted in Windows Azure

Using WIF & WCF tracing for a WCF service hosted in Windows Azure, taking advantage of blob storage for the traces

Configure a WCF service to use load balancing

Deploy a WCF service secured via WIF to the Windows Azure cloud

Windows Identity Foundation can do much more than what we cover in this lab: we hope that the skills you will learn here will help you in your further explorations of identity development.

The first lab will show you the process to configure a weather service to trust an on-premises development STS, and run the entire solution in the Compute Emulator. The second lab will add diagnostics and load balancing features to the WCF service implemented in the first lab. Finally, the third lab will walk you through the steps for running the solution to Windows Azure, which trusts an on-premises STS, generates diagnostic logs, and provides load balancing facilities. As shown on the figure below, an already provided client will be used to consume the WCF service running on the Compute emulator and afterwards in Windows Azure.

Page 4: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 1A visual summary of what you will build in this lab

Objectives

In this hands-on lab, you will learn how to:

Use Windows Identity Foundation for handling access to a WCF service hosted in the Windows Azure DevFabric by reusing on-premises identities

Add STS references on a WCF service hosted in Windows Azure

Add service references to a client which points to a WCF service hosted in Windows Azure

Configure a WCF service to emit WIF and WCF traces in blob storage, and retrieve traces for offline analysis

Provide custom SecurityTokenHandler and ServiceBehavior classes for enabling a WCF service to take advantage of load balancers

Deploy to the Windows Azure staging and production evnironments a WCF service secured via WIF

Page 5: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

System Requirements

You must have the following items to complete this lab:

Microsoft® Windows® Vista SP2 (32-bits or 64-bits) or Microsoft® Windows Server 2008 SP2 (32-bit or 64-bit) with KB971842 (http://support.microsoft.com/kb/971842), or Microsoft® Windows® 7 (32-bits or 64-bits) or Microsoft® Windows Server 2008 R2 (64-bits) with KB977420 (http://support.microsoft.com/kb/977420).

Microsoft® Internet Information Services (IIS) 7.0 (with ASP.NET component, Static Content Support, and a Localhost SSL certificate installed)

Microsoft® .NET Framework 4.0

Microsoft® Visual Studio 2010

Windows Azure Tools for Microsoft Visual Studio 1.4

Microsoft® Windows Identity Foundation Runtime

Microsoft® Windows Identity Foundation SDK 4.0

Setup

In order to execute this hands-on lab exercises you need to setup this lab.

Note: Make sure you have checked all the dependencies for this lab before running the setup.

1. Open a Windows Explorer window and browse to the lab’s root folder.

2. Double-click the Setup.cmd file in this folder to launch the setup process that will configure your environment and install the Visual Studio code snippets for this lab. This will also install the localhost certificate used in the second exercise by the local STS.

3. If the User Account Control dialog is shown, confirm the action to proceed.

4. The setup script will proceed with the certificates installation. Press Y if you want to continue with the required certificates installation.

Note: If you already have a "localhost" certificate needed by another application, ensure to make a backup copy of it before continue with the lab's certificates installation.

Page 6: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 2Certificates installation finished

Note: If you are running Windows 7 or Windows 2008 R2 you might not see this window.

5. When finished press any key to close the setup console.

Note: In addition to the setup script, inside the Source\Setup folder of this lab, there is a Cleanup.cmd file you can use to uninstall all the code snippets installed by setup scripts.

Using the Code Snippets

Throughout the lab document, you will be instructed to insert code blocks. For your convenience, most of that code is provided as Visual Studio Code Snippets, which you can use from within Visual Studio 2010 to avoid having to add it manually.

If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the Setup.docx document in the Assets folder of the training kit, which contains a section describing how to use them.

Exercises

The following exercises make up this hands-on lab:

1. Using the Windows Identity Foundation with a WCF Service in Windows Azure

2. Adding Diagnostics and Load Balancing

Page 7: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

3. Deploying the WCF Service to Windows Azure

Note: Inside each exercise you will find an end folder where you find the resulting solution you should obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises.

Estimated time to complete this lab: 60 minutes

Note: When you first start Visual Studio, you must select one of the predefined settings collections. Every predefined collection is designed to match a particular development style and determines window layouts, editor behavior, IntelliSense code snippets, and dialog box options. The procedures in this lab describe the actions necessary to accomplish a given task in Visual Studio when using the General Development Settings collection. If you choose a different settings collection for your development environment, there may be differences in these procedures that you need to take into account.

Getting Started: Setting up the Certificates and Local STS

Task 1 - Generating the Required Certificates

During this task, you will create an X.509 certificate used by the service you will implement in the Exercises of this lab. Your service will need a certificate in order to be able to publish endpoints on a SSL channel; the same certificate will be used for handling token encryption and decryption. Windows Azure expects to find X.509 certificates for cloud solutions in specific stores, hence it will be necessary to register your service certificate accordingly. Note that in a real application you would probably obtain a certificate from a trusted certificate authority, and that the subject name would follow whatever DNS name you want to ultimately assign to your service. For the sake of simplicity, in this lab we will provide you with scripts for generating self-signed certificates which are not suitable for production use.

To do this, you will execute a script provided as part of the assets of the Lab.

1. Open a Microsoft Visual Studio 2010 Command Prompt with administrator privileges. From Start | All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools, right-click Visual Studio 2010 Command Prompt and select Run as administrator.

2. Navigate to the Assets\AzureCertificates folder inside the Source folder of this Lab.

Page 8: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

3. Execute the SetupCertificates.cmd script. The name you provide will be used as the subject of the generated certificate, in the form {yourprojectname}.cloudapp.net. Since we plan to use SSL, the subject must correspond to the URI of the application if you want to prevent warnings about mismatches. Remember that if you plan to deploy to the cloud, the name you pick must be unique: we suggest to use a name of a form that will remind you of the project’s purpose, such as wifwcfwazlab{companyname}.cloudapp.net. Make sure to use only lower case letters.

Note: During this lab, “foo” will be used as sample service project name. When you see it, you should provide the name that you used to create your Windows Azure Hosted Service.

IMPORTANT: If the name you pick at this point will end up being already in use, if you want to perform the last task of the lab (deploy to the public cloud) you will need to choose a new, unique name and repeat various steps in the lab.

CMD

SetupCertificates.cmd

Note: This script will perform the following tasks:

- Create a certificate for your Relying Party (RP) application using the MakeCert command and store it in the LocalMachine\Personal store.

- Copy the generated certificate to the CurrentUser\Personal store so the Windows Azure Tools for Visual Studio can find it.

- Copy the localhost certificate generated by Windows Azure SDK to the LocalMachine\Trusted Root store, so svcutil and “Add Service Reference“ (used later in the lab) can connect to HTTPS metadata endpoints hosted in Compute Emulator. Note that, if this is the first time that you use the Windows Azure SDK on your machine, the certificate here mentioned may not have been already created: in that case you may need to perform extra steps later in the exercise.

Page 9: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 3A visual summary of what you will build in Exercise 1

Note: This script relies on Windows PowerShell scripts in its underlying implementation. In order to run those scripts, PowerShell execution policy must be set to Unrestricted. By default, PowerShell’s execution policy is set to Restricted; that means that scripts - including those you write yourself - won’t run. If needed, run the command below in an Administrator PowerShell command prompt to set your execution policy to Unrestricted (all scripts will run, regardless of where they come from and whether or not they’ve been signed.

Set-ExecutionPolicy RemoteSigned

For more information, take a look at the following MSDN article: http://technet.microsoft.com/en-us/library/ee176949.aspx

4. Close the command prompt.

Task 2 - Creating the local STS

Exercises in this lab need an STS to which you can outsource authentication to. You may have access to some local identity provider, for example your company’s instance of ADFSv2, however that is not always the case. In order to ensure that you can successfully go through the lab without dependencies, we will make sure that you have access to a suitable identity provider by giving you instructions to

Page 10: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

create your own development time STS, hosted in your local IIS. WIF makes the task extremely easy, by providing a WCF project template which already contains most of the plumbing you need. Note that the STS you are building here can be used with on-premises services just as well.

Note: If you do have an STS available in your environment, feel free to use it instead of creating one through this task. Just make sure to do it only if you know that your STS provides the necessary capabilities for the lab scenario and that you are confident enough in the topic to be able to adjust the instructions in the next tasks accordingly.

1. Open Microsoft Visual Studio 2010 with administrator privileges. From Start | All Programs | Microsoft Visual Studio 2010, right-click Microsoft Visual Studio 2010 and select Run as administrator.

2. In the File menu, select New | Web Site.

3. In the New Web Site dialog, select the WCF Security Token Service template and press the Browse button at the right of the Location text box.

Figure 4Creating the WCF Security Token Service

4. In the Choose Location dialog, select Local IIS at the left panel. You will create a new Web Application to host the STS, to do this, select the Default Web Site node on the tree at the right

Page 11: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

and press the Create New Web Application button ( ). Set the name to LocalSTS and make sure that the Use Secure Sockets Layer option is checked.

Figure 5Creating the new Web Application to host the STS

5. Press Open to confirm the location and OK to finally create the STS.

6. The development STS does not issue encrypted tokens by default: we need to go back to the STS project and change the STS configuration accordingly. Open the Web.config file of the https://localhost/LocalSTS project by double-clicking it in the Solution Explorer.

7. Inside the <appSettings> section, set the signing certificate used by the STS by modifying the SigninigCertificateName property as it is shown below. Set its value to “IdentityTKStsCert” which is the CN for the certificate created as part of the setup for this Lab.

XML

<appSettings> <add key="IssuerName" value="ActiveSTS"/> <add key="SigningCertificateName" value="CN=IdentityTKStsCert"/> <add key="EncryptingCertificateName" value

Page 12: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

="CN=DefaultApplicationCertificate"/> </appSettings>

8. Inside the <appSettings> section, set the certificate used by the STS to the one created for the Relying Party in previous task, modifying the EncryptingCertificateName property as it is shown below. Remember to update the placeholder with your actual Windows Azure Hosted Service name you used in the previous task.

XML

<appSettings> <add key="IssuerName" value="ActiveSTS"/> <add key="SigningCertificateName" value="CN=IdentityTKStsCert"/> <add key="EncryptingCertificateName" value ="CN={yourprojectname}.cloudapp.net"/> </appSettings>

9. Metadata retrieval from the STS will be over https. To enable this, replace the httpGetEnabled attribute inside the serviceMetadata element to httpsGetEnabled (note the “s”):

XML

<system.serviceModel> ... <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors></system.serviceModel>

Note: Here we are changing the metadata retrieval to take place on https simply because it is good practice. It is by no means a Windows Azure-specific requirement; we may do the same on-premises.

10. Also update the Mex endpoint to use the mexHttpsBinding binding (note the “s”):

XML

<system.serviceModel> <services>

Page 13: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

<service name="Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract" behaviorConfiguration="ServiceBehavior"> <endpoint address="IWSTrust13" binding="ws2007HttpBinding" contract="Microsoft.IdentityModel.Protocols.WSTrust.IWSTrust13SyncContract" bindingConfiguration="ws2007HttpBindingConfiguration"/> <host> ... </host> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /> </service> </services> ...</system.serviceModel>

11. Press Ctrl + S to save the Web.config file and close it.

Exercise 1: Using Windows Identity Foundation with a WCF Service in Windows Azure

This exercise will walk you through the process of creating a WCF role, configure its service to trust an on-premises development STS, attach a client and run the entire solution in the Compute Emulator. This is easily accomplished with only minor modifications to the procedure you would have followed for obtaining the same result on premises. The main changes accommodate the fact that in Windows Azure a service is hosted at different addresses according to the environment (local, staging, production), a situation you would have to deal with in any multi-staged environment.

You will start in Task 1 by implementing a simple weather service and testing its behavior without authentication using a client provided by the lab. Afterwards in Task 2, you will use WIF tooling to establish a trust relationship between the weather service and a local STS, by configuring the WCF service binding and behaviors collection in a way that will make the service require tokens from LocalSTS from all its future callers. Then in Task 3 and 4, you will set up an HTTPS secure endpoint between the WCF service and the STS using an X.509 certificate, using the Windows Azure Visual Studio tooling UI for associating it to the RelyingParty WCF Service Role. You will also enable the weather service HTTPS endpoint port. Finally in the verification, you will update the client to test the HTTPS endpoint of the weather service.

Page 14: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Task 1 – Implementing the Weather Service

The sample Relying Party application you will build in this lab will simulate a service providing weather-related information, hosted on a WCF Role of Windows Azure. In this task, you will open a Windows Azure Project project with a WCF Role already created. Then, you will implement the Weather Service and verify its behavior using a client provided by the lab.

Note: You require an STS project and appropriate certificates to complete this exercise. If you have not already done so, complete the Getting Started section.

1. Open Microsoft Visual Studio 2010 with administrator privileges. From Start | All Programs | Microsoft Visual Studio 2010, right-click Microsoft Visual Studio 2010 and select Run as administrator.

2. Open the WIFWCFonWindowsAzure.sln solution file from the \Source\Ex1-UsingWIFandWCF\Begin folder of this lab.

3. You will first setup some basic configuration for running the WCF Role. In the Solution Explorer, double-click the RelyingParty node inside the Roles folder of the CloudConfiguration project to bring up its properties page.

4. In the Configuration tab, make sure that .NET trust level is set to Full Trust, and uncheck the HTTP endpoint check box inside the Startup action section to avoid launching the browser when you run the CloudConfiguration project.

Note: If you can’t uncheck the HTTP endpoint check box, close Visual Studio, and open it again as Administrator.

Page 15: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 6Configuration for not launching the browser.

5. Now, you will set the WCF Service Web Role endpoints configuration. To do this, select the Endpoints tab and set the Public Port to 8000 for Endpoint1. This will make the service to be available in port 8000.

Figure 7Configuring HTTP WeatherService endpoint

Note: The port value above are meant to avoid collisions with other processes listening for connections on the local machine. A typical example of this would be IIS, which usually reserves the use of ports 80 and 443 for itself. If you pick ports that collide with ports already in use by other processes, DevFabric will assign to your service random ports making

Page 16: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

development difficult. If port 8000 is already in use in your machine, make sure you choose a different port accordingly.

6. You will now provide an implementation of the weather service. To do this, right-click the RelyingParty project and select Add | Existing Item.

7. In the Add Existing Item dialog, navigate to the Assets\Service folder inside the Source folder of this lab, select the IWeatherService.cs and WeatherService.svc files and press Add. These files set up a weather service, which provides random 3 and 10 day forecasts based on a given zip code.

Figure 8Adding WeatherService files to the RelyingParty

8. You will now test the service behavior using the Client project that is already included in the solution. To do this, press Ctrl + F5 to run the Cloud project without attaching the Visual Studio debugger. The Compute Emulator and the Storage Emulator will be launched.

Page 17: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 9Opening the Compute Emulator UI

9. Right-click the Azure icon tray and select Show Compute Emulator UI. In the Windows Azure Compute Emulator, ensure that the service has started successfully browsing the tree at the left panel looking for the RelyingParty role.

Figure 10Checking that the RelyingParty role is running correctly

10. Back in Visual Studio, right-click the Client project and select Add Service Reference. The service will be listening on the localhost (127.0.0.1) on the port we specified in previous steps, that is to say 8000. Enter http://127.0.0.1:8000/WeatherService.svc on the Address text box, and then press Go.

Page 18: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 11Adding a Service reference to the RelyingParty running on Compute Emulator

11. Leave the default Service Namespace and press OK to add the reference to the WCF Service.

12. You will now set up the Client project that is included in the solution to consume the weather service you just added. To do this, right-click the ForecastForm node, select View Code, and add the following statement.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex01 ForecastForm using statement)

C#

using Client.ServiceReference1;

13. Replace the ShowForecast method implementation with the following code:

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex01 ForecastForm consuming weater service)

C#

Page 19: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

private void ShowForecast(int days, int zipCode){ using (WeatherServiceClient relyingParty = new WeatherServiceClient()) { WeatherInfo weatherInfo = null;

try { this.Cursor = Cursors.WaitCursor; this.sourceLabel.Text = "Loading...";

if (days == 3) { weatherInfo = relyingParty.GetThreeDaysForecast(zipCode); } else if (days == 10) { weatherInfo = relyingParty.GetTenDaysForecast(zipCode); }

this.DisplayForecast(weatherInfo.Forecast); this.sourceLabel.Text = string.Format( CultureInfo.InvariantCulture, "Source: {0}", weatherInfo.Observatory); } catch (MessageSecurityException ex) { this.sourceLabel.Text = string.Empty; MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); relyingParty.Abort(); } finally { this.Cursor = Cursors.Default; } }}

private void DisplayForecast(Weather[] forecast){ this.forecastPanel.Controls.Clear();

for (int i = 0; i < forecast.Length; i++) { PictureBox pic = new PictureBox();

Page 20: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

GroupBox box = new GroupBox();

box.Text = string.Format( CultureInfo.CurrentCulture, "{0:ddd dd}: {1}", DateTime.Today.AddDays(i), forecast[i]); box.Height = 145; box.Width = 130; pic.Dock = DockStyle.Fill; pic.SizeMode = PictureBoxSizeMode.CenterImage; box.Controls.Add(pic);

switch (forecast[i]) { case Weather.Sunny: pic.Image = Resources.Sunny; break; case Weather.Cloudy: pic.Image = Resources.Cloudy; break; case Weather.Snowy: pic.Image = Resources.Snowy; break; case Weather.Rainy: pic.Image = Resources.Rainy; break; }

this.forecastPanel.Controls.Add(box); }}

14. To test the weather service behavior without authentication, right-click the Client project and select Debug | Start new instance.

15. In the Weather Station client, enter any Zip Code (for example: 1000) and press the Get 3 Days button. You should get the forecast for the following 3 days.

Page 21: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 12Getting the forecast for the following 3 days (note that the port number might be different)

16. Close the Weather Station client.

Stop the WCF Service Web Role running on Compute Emulator from its UI. To do this, right-click the Compute Emulator and Storage icon on the Windows’ tray bar and select Show Compute Emulator UI. In the tree at the left panel, right-click the current deployment and select Remove.

Task 2 – Establishing a Trust Relationship between the WCF Service and the Development STS

Now that we have the WCF service running and the STS, it’s time to establish a trust relationship between them. In practical terms, that means that the WCF service binding and behaviors collection will be configured in a way that will make the service require tokens from LocalSTS from all its future callers. The bulk of the task will be performed by the WIF tooling, and specifically the Add STS Reference wizard (which in turn is the Visual Studio integration of fedutil.exe, a standalone tool provided in the WIF SDK).

1. Open the Web.config file of the RelyingParty project by double-clicking it in the Solution Explorer.

2. The fedutil.exe tool expects to find the WCF service configuration within the local Web.config file. But since WCF for .Net Framework 4 relies on a machine level configuration file, a temporal service element needs to be added to the default configuration. To do this, add the following services configuration inside the <system.serviceModel> section.

XML

<system.serviceModel> <services> <service name="RelyingParty.WeatherService"> <endpoint address=""

Page 22: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

binding="basicHttpBinding" contract="RelyingParty.IWeatherService" /> </service> </services>

...

3. Press Ctrl + S to save the Web.config file and close it.

4. Right-click the RelyingParty project and select Add STS reference. The Federation Utility will be displayed.

Note: If the Add STS Reference item is not shown in the contextual menu within Visual Studio 2010, you can manually launch the tool by executing the fedutil.exe command found in %ProgramFiles%\Windows Identity Foundation SDK\v4.0. Browse and select the RelyingParty Web.config as the Application configuration location.

Page 23: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

5. Enter https://{yourprojectname}.cloudapp.net/ as Application URI, changing the {yourprojectname} placeholder for your Windows Azure Hosted Service name, and press Next.

Figure 13Specifying the project’s Application URI

Page 24: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

6. Press Next in the Application Information Wizard step.

Figure 14Selecting the service to configure

7. Here you specify the address of the STS you want to outsource authentication to, that is to say the LocalSTS project you created in the previous task. To do this, select the Use an Existing STS option. Set the metadata document location to https://localhost/LocalSTS and press the Test Location button (make sure not to include spaces at the end of the metadata document location field).

The wizard will inspect the STS site searching for a metadata document and will find the FederationMetadata.xml file, which will be shown in a new browser instance. The full file path will be added in the metadata document location field in the wizard window. Close the browser and press Next.

Page 25: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 15Using existing STS created on the previous task

8. In Security token encryption, choose Enable encryption. Use the certificate created on the Getting Started: Setting up the Certificates and Local STS section for the Relying Party selecting the Select an existing certificate from store option and pressing the Select Certificate button.

In the Select certificate dialog, chose the {yourprojectname}.cloudapp.net certificate and press OK. Press Next to continue with the wizard.

Page 26: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 16Configuring encryption for the communication with the STS

9. Press Next in the Offered Claims Wizard step.

Page 27: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 17Showing Offered claims by the STS

Note: The Offered claims dialog lists all the claims that a RP application can request to the STS. Name and Role are the default claims which are hardcoded in the WIF STS template: if you would be running the wizard against a proper STS, for example an ADFSv2 instance in your organization, the list would change accordingly.

10. Check the Wizard summary, and press Finish.

Task 3 – Adding the Certificates to the Relying Party

In the following steps you are going to configure the certificate created on the Getting Started: Setting up the Certificates and Local STS section, using the Windows Azure Visual Studio tooling UI for associating it to the RelyingParty WCF Service Role.

1. In the Solution Explorer, double-click the RelyingParty node inside the Roles folder of the CloudConfiguration project to bring up its properties page.

2. Select the Certificates tab. Add a new certificate clicking the Add Certificate button at the top of the page. Set the certificate’s name to {yourprojectname}.cloudapp.net and then click the button labeled with an ellipsis (...) of the Thumprint column.

Page 28: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 18Creating the Relying Party’s certificate

3. In the Select a certificate dialog, choose the certificate named {yourprojectname}.cloudapp.net and press OK.

Figure 19Configuring the certificate to the Relying Party. Note that the certificates listed here are all from the LocalMachine\Personal store

4. Now, you will set the HTTPS WCF Service Web Role endpoint configuration. Select the Endpoints tab to enter to the endpoints’ configuration page.

5. Click the Add Endpoint button. In the name column fill with HttpsIn, set the protocol to https, set Public Port to 8443 name and chose the {yourprojectname}.cloudapp.net certificate from the SSL Certificate name combo box.

Page 29: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 20Configuring endpoints for the Relying Party

Note: The port values above are meant to avoid collisions with other processes listening for connections on the local machine. A typical example of this would be IIS, which usually reserves the use of ports 80 and 443 for itself. If you pick ports that collide with ports already in use by other processes, DevFabric will assign to your service random ports making development difficult. If ports 8000 and 8443 are already in use in your machine, make sure you choose different ports accordingly.

6. Select the Configuration tab, and uncheck both check boxes inside the Startup action section to avoid launching the browser for the HTTP and HTTPS endpoints when you run the CloudConfiguration project.

Figure 21

Page 30: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Relying Party general configuration

7. Press Ctrl + S to save the modified properties for the RelyingParty Role.

8. Close the RelyingParty Role property page.

Task 4 – Configuring the WCF Service HTTPS Endpoint

In this task you will update the WCF Weather Service to use the HTTPS endpoint.

1. Open the Web.config file of the RelyingParty project.

2. Add a name to the behavior element as shown in the code below. Make the name of the behavior RelyingParty.WeatherServiceBehavior:

XML

<system.serviceModel> … <behaviors> <serviceBehaviors> <behavior name="RelyingParty.WeatherServiceBehavior"> …</system.serviceModel>

3. Add the configuration behavior for KB971842 to the behavior named RelyingParty.WeatherServiceBehavior inside the <system.serviceModel> configuration section.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex01 Configuration behavior)

XML

<system.serviceModel> … <behaviors> <serviceBehaviors> <behavior name="RelyingParty.WeatherServiceBehavior"> … <serviceCredentials> … </serviceCredentials> <useRequestHeadersForMetadataAddress> <defaultPorts> <add scheme="http" port="8000" /> <add scheme="https" port="8443" /> </defaultPorts> </useRequestHeadersForMetadataAddress>

Page 31: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

</behavior> </serviceBehaviors> </behaviors>

Note: WCF 3.5 default metadata publishing mechanisms do not work too well in Windows Azure. The issue is in the way in which URIs are included in WSDL documents: the default behavior will include the internal ports used by the Windows Azure load balancer, which are not addressable from external callers. As a result, you cannot simply create a service reference using the standard tools (svcutil or add service reference in Visual Studio). The issue is described in a KB article, which provides a hotfix for resolving the problem. The hotfix is listed among the prerequisites for the lab. The useRequestHeadersForMetadataAddress behavior configuration enables the hotfix and induces WCF to use the load balancer’s address instead of one internal node address.

You can find further information at http://support.microsoft.com/kb/971842/.

4. The wizard configured the service to use ws2007FederationHttpBinding, however we need to exercise more control in the way in which we handle messages. Remove the current ws2007FederationHttpBinding section inside bindings and add the following custom binding. Remember to update {yourprojectname} label with your Windows Azure Hosted Service name.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab – Ex01 CustomBinding)

XML

<system.serviceModel> … <bindings> <customBinding> <binding name="RelyingParty.IWeatherService"> <security authenticationMode="SecureConversation" messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10" requireSecurityContextCancellation="false"> <secureConversationBootstrap authenticationMode="IssuedTokenOverTransport" messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"> <issuedTokenParameters> <additionalRequestParameters> <AppliesTo xmlns="http://schemas.xmlsoap.org/ws/2004/09/policy"> <EndpointReference xmlns="http://www.w3.org/2005/08/addressing">

Page 32: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

<Address>https://{yourprojectname}.cloudapp.net/</Address> </EndpointReference> </AppliesTo> </additionalRequestParameters> <claimTypeRequirements> <add claimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" isOptional="true" /> <add claimType="http://schemas.microsoft.com/ws/2008/06/identity/claims/role" isOptional="true" /> </claimTypeRequirements> <issuerMetadata address="https://localhost/LocalSTS/Service.svc/mex" /> </issuedTokenParameters> </secureConversationBootstrap> </security> <httpsTransport /> </binding> </customBinding> <ws2007FederationHttpBinding> <binding name="RelyingParty.IWeatherService_ws2007FederationHttpBinding"> <security mode="Message"> <message> <issuerMetadata address="https://localhost/LocalSTS/Service.svc/mex" /> <claimTypeRequirements> <add claimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" isOptional="true" /> <add claimType="http://schemas.microsoft.com/ws/2008/06/identity/claims/role" isOptional="true" /> </claimTypeRequirements> </message> </security> </binding> </ws2007FederationHttpBinding> </bindings></system.serviceModel>

Note: The main reason for which we need a custom binding is that we want to set the attribute requireSecurityContextCancellation of the <security> element to false hence moving to cookie mode. This will allow you, later in the lab, to take control of the session token and accommodate its processing to the load balanced environment of Windows Azure.

Page 33: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

5. Add the behaviorConfiguration attribute to the service named RelyingParty.WeatherService.

XML

<system.serviceModel> <services> <service name="RelyingParty.WeatherService" behaviorConfiguration="RelyingParty.WeatherServiceBehavior"> … </services></system.serviceModel>

6. Remove the hardcoded address created by Federation Utility from the endpoint configuration. To do this, replace the endpoint element with the one highlighted below:

XML

<system.serviceModel> <services> <service name="RelyingParty.WeatherService" behaviorConfiguration="RelyingParty.WeatherServiceBehavior"> <endpoint address="https://{yourProjectName}.cloudapp.net/" binding="ws2007FederationHttpBinding" contract="RelyingParty.IWeatherService" bindingConfiguration="RelyingParty.IWeatherService_ws2007FederationHttpBinding" /> <endpoint address="" binding="customBinding" contract="RelyingParty.IWeatherService" bindingConfiguration="RelyingParty.IWeatherService" />

... </service> </services> ...</system.serviceModel>

7. Also add Mex endpoint that use the mexHttpsBinding binding (note the “s”):

XML

<system.serviceModel> <services> <service name="RelyingParty.WeatherService" behaviorConfiguration="RelyingParty.WeatherServiceBehavior"> <!--<endpoint address="https://foo.cloudapp.net/" binding="ws2007FederationHttpBinding" contract="RelyingParty.IWeatherService" bindingConfiguration="RelyingParty.IWeatherService_ws2007FederationHttpBinding" />-->

Page 34: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

<endpoint address="" binding="customBinding" contract="RelyingParty.IWeatherService" bindingConfiguration="RelyingParty.IWeatherService" />

<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />

</service> </services></system.serviceModel>

8. The metadata retrieval from the WCF Service Web Role will also be over https. To enable this, replace the httpGetEnabled attribute inside the serviceMetadata element with httpsGetEnabled (note the “s”):

XML

<system.serviceModel> ... <behaviors> <serviceBehaviors> <behavior name="RelyingParty.WeatherServiceBehavior"> <federatedServiceHostConfiguration name="RelyingParty.WeatherService" /> <serviceMetadata httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> <serviceCredentials> ... </serviceCredentials> <useRequestHeadersForMetadataAddress> ... </useRequestHeadersForMetadataAddress> </behavior> </serviceBehaviors> </behaviors></system.serviceModel>

9. Update the thumbprint attribute value for the LocalSTS trusted issuer with the one shown below. This is the thumbprint of the certificate that the LocalSTS is using for signing.

XML

<microsoft.identityModel> <service name="RelyingParty.WeatherService"> <audienceUris> <add value="https://{yourprojectname}.cloudapp.net/" /> </audienceUris>

Page 35: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

<issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <trustedIssuers> <add thumbprint="40A1D2622BFBDAC80A38858AD8001E094547369B" name="https://localhost/LocalSTS/Service.svc" /> </trustedIssuers> </issuerNameRegistry> </service> </microsoft.identityModel>

10. Press Ctrl + S to save the Web.config file and close it.

11. You will configure the WeatherService to listen for request in any address where it is available. To do this, open the WeatherService.svc.cs file for the RelyingParty project, and add a ServiceBehavior attribute to the WeatherService class definition as it is shown on the following code.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex01 ServiceBehavior attribute)

C#

namespace RelyingParty{ [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)] public class WeatherService : IWeatherService { ... }}

Note: Decorating your service class with that attribute has the effect of turning off the address filter, so that incoming messages with different To elements are accepted.

12. Press Ctrl + S to save the WeatherService.svc.cs file and close it.

Verification

Your service is finally ready to run using the certificates. You will now update the client to consume the project using the HTTPS encrypted endpoint.

In order to verify that you have performed every step in the exercise correctly, proceed as follows:

Page 36: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

1. Press Ctrl + F5 to run the Cloud project without attaching the Visual Studio debugger. The DevFabric will be launched. Proceed as in Task 1 to verify in the Compute Emulator that the service has started successfully.

2. In the Client project, right-click the ServiceReference1 node inside the Service References folder and select Configure Service Reference.

Figure 22Configuring the Client service reference

3. The service will now be listening on the localhost (127.0.0.1) on the SSL port we specified in the earlier tasks, that is to say 8443. Enter https://127.0.0.1:8443/WeatherService.svc on the Address text box and press OK.

Page 37: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 23Weather Service configuration update

Note: If it is the first time that you configure https bindings on Compute Emulator, you will get the following warning:

Page 38: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

To work around it, you have to copy the 127.0.0.1 certificate created by Windows Azure Tools for Visual Studio (which is available at LocalMachine\Personal store) to the LocalMachine\Trusted Root store. You can do that by using the certificates MMC in Windows.

Another way to work around this is running again the SetupCertificate.cmd script, without providing any Windows Azure Hosted Service name. The script will copy the 127.0.0.1 certificate to LocalMachine\Trusted Root for you.

Once you successfully performed one of the steps above, you can repeat the service reference step.

4. Open the app.config file inside the Client project.

5. Move the AppliesTo element from the trust:SecondaryParameters section to additionalRequestParameters. Remember to update {yourprojectname} label with your Windows Azure Hosted Service name.

XML

<system.serviceModel> <bindings> <customBinding> <binding name="CustomBinding_IWeatherService"> <security ...> <localClientSettings .../> <localServiceSettings .../> <secureConversationBootstrap ...> <issuedTokenParameters> <additionalRequestParameters> <AppliesTo xmlns="http://schemas.xmlsoap.org/ws/2004/09/policy"> <EndpointReference xmlns="http://www.w3.org/2005/08/addressing"> <Address>https://{yourprojectname}.cloudapp.net/</Address> </EndpointReference> </AppliesTo> <trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512"> … <AppliesTo xmlns="http://schemas.xmlsoap.org/ws/2004/09/policy"> <EndpointReference xmlns="http://www.w3.org/2005/08/addressing"> <Address>https://{yourprojectname}.cloudapp.net/</Address> </EndpointReference> </AppliesTo>

Page 39: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

</trust:SecondaryParameters> </additionalRequestParameters> </issuedTokenParameters> </secureConversationBootstrap> </security> </binding> </customBinding> </bindings></system.serviceModel>

Note: The RP provides indications about the desired AppliesTo value in the SecondaryParameters element, and svcutil does capture it in the client configuration. However the client has to explicitly accept the settings by moving them in the RST: after all, a compromised RP may try to spoof the token by providing malicious addresses overriding the AppliesTo.

6. The client is finally ready to call the RelyingParty WCF Service. To test it, right-click the Client project and select Debug | Start new instance.

7. In the Weather Station client, enter any Zip Code (for example: 1000) and press the Get 3 Days button. You should get the forecast for the following 3 days. Note that now the Source uses the https port.

Figure 24Getting the forecast for the following 3 days (note that the port number might be different)

8. Close the Weather Station client.

Page 40: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

9. Stop the WCF Service Web Role running on Compute Emulator from its UI. To do this, right-click the Compute Emulator and Storage icon on the Windows’ tray bar and select Show Compute Emulator UI. In the tree at the left panel, right-click the current deployment and select Remove.

Note: In this first set of tasks you developed a simple but complete scenario. You created a certificate for your service, a cloud project with your WCF role and a local development STS. You learned how to use the WIF tooling for outsourcing the service authentication to an STS, what practicalities need to be handled for preparing a WCF service to run in Windows Azure and how to develop a client for the service. Finally, you verified that everything works by running the service in the DevFabric environment. That’s pretty much all you need to know for getting started to host in Windows Azure your own services and secure them; in the following Exercises we will explore more advanced aspects of the WIF and WCF synergy in Windows Azure.

Exercise 2: Adding Diagnostics and Load Balancing

We always hope that everything will work as expected at first attempt, and that it will keep going without a hitch. However we know that the reality is different: systems need to be troubleshot, especially when they are still in development phase. Cloud hosted services pose specific challenges on this aspect, since various traditional techniques (such as attaching a debugger to the service) are not readily available. Luckily both WIF and WCF offer very comprehensive tracing features, which can be used for handling diagnostics for your services. All you need to do for taking advantage of the diagnostic features of WIF and WCF in Windows Azure is writing traces by leveraging features of the platform, such as blob storage.

The procedure is quite similar to what you would have done on premises: the key difference is that in Windows Azure we save the traces in Blob storage.

After having seen how tracing works, we will give you indications on how to configure WIF on your WCF service in order to take advantage of a load balanced environment regardless of its size (from a local 2-machines rig to the arbitrarily big setups you can obtain in Windows Azure).

Task 1 – Adding Diagnostics Support

Page 41: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

In this task will take advantage of the diagnostic features of WIF and WCF in Windows Azure, by augmenting the solution you built on the previous exercise with diagnostic features. You configure the WCF Web Role to generate diagnostic trace logs for the Weather Service.

Note: You require an STS project and appropriate certificates to complete this exercise. If you have not already done so, complete the Getting Started section.

1. Open Microsoft Visual Studio 2010 with administrator privileges. From Start | All Programs | Microsoft Visual Studio 2010, right-click Microsoft Visual Studio 2010 and select Run as administrator.

Note: If you performed all the steps from Exercise 1: Using Windows Identity Foundation with a WCF Service in Windows Azure, you can continue using the solution you obtained after completing that exercise and skip to step 5.

2. Open the WIFWCFonWindowsAzure.sln solution file from the \Source\Ex2-DiagnosticsAndLoadBalancing\Begin folder of this lab.

3. Replace the following placeholders in all solution files. To do this, you can use Visual Studio’s Quick Replace dialog (Edit | Find and Replace | Quick Replace).

◦ Replace the {yourProjectName} placeholder with the name you use for the certificate and the azure project (e.g.: foo)

◦ Replace the {yourCertificateThumbprint} placeholder with the thumbprint of the {yourprojectname}.cloudapp.net certificate you created during the Getting Started: Setting up the Certificates and Local STS section (e.g.: 939026E4657552526FXXXX868DEA80F788991A73)

◦ Replace the {yourMachineName} placeholder with the name of your machine.

Note: You can get more information on how to retrieve the thumbprint of your certificate from the How to: Retrieve the Thumbprint of a Certificate MSDN article.

Page 42: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 25Replacing begin solution placeholders

4. Double-click the RelyingParty node inside the Roles folder of the CloudConfiguration project. Select the Configuration tab, and uncheck both check boxes inside the Startup action section to avoid launching the browser for the HTTP and HTTPS endpoints when you run the CloudConfiguration project.

Note: If you can’t uncheck the HTTP endpoint check box, close Visual Studio, and open it again as Administrator.

Page 43: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 26Relying Party general configuration

5. Select the Settings Tab. Add a new setting clicking the Add Setting button at the top. Set the new setting’s name to Deployment and its value to Development.

Figure 27Adding the new Deployment setting

Page 44: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Note: Windows Azure solutions can be executed on three different environments: DevFabric, staging and production. All those three have some intrinsic characteristic that will differ, such as the full address at which the WCF service will listen. This will often force your application to switch between different alternative WIF configurations: if you name those configurations and define a settings string tied to it, you can then easily switch between alternative configurations without the need of modifying and redeploying the solution.

6. When you create a new Windows Azure solution, it creates the necessary infrastructure for taking advantage of the diagnostic features. Explore the following diagnostics infrastructure on the solution:

◦ Local Storage is configured to be used. You can verify this in Local Storage tab of the RelyingParty configuration, where the RelyingParty.svclog storage is set.

◦ A default trace listener AzureLocalStorageTraceListener class is created within the project structure, which defines wad-tracefiles as the directory where to store the generated trace logs on the Windows Azure Local Storage.

◦ The OnStart method on the WebRole class configures the role to flush trace logs to the blob storage once per minute, and adds the folder defined by AzureLocalStorageTraceListener to the diagnostic directories.

7. For performance reasons, diagnostics is disabled by default. To enable it, uncomment the following code from the Web.config of the RelyingParty project, which sets the usual diagnostic APIs as if the service would be hosted on-premises (note that you have to delete the closing </system.diagnostic> tag and the opening <system.diagnostic> tag).

XML

<!-- To collect diagnostic traces, uncomment the section below. To persist the traces to storage, update the DiagnosticsConnectionString setting with your storage credentials. To avoid performance degradation, remember to disable tracing on production deployments. --><system.diagnostics> <sharedListeners> <add name="AzureLocalStorage" type="Rely.AzureLocalStorageTraceListener, Rely"/> </sharedListeners> <sources> <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing"> <listeners>

Page 45: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

<add name="AzureLocalStorage"/> </listeners> </source> <source name="System.ServiceModel.MessageLogging" switchValue="Verbose"> <listeners> <add name="AzureLocalStorage"/> </listeners> </source> </sources> </system.diagnostics> <system.diagnostics>

8. Add the autoflush attribute to the trace element and set it to true.

XML

<system.diagnostics> <sharedListeners> … </sharedListeners> <sources> … </sources> <trace autoflush="true"> <listeners> … </listeners> </trace></system.diagnostics>

9. Additionally, to include Windows Identity Framework tracing add the following source to the sources of the system.diagnostics you have just added.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex02 MicrosoftIdentityModel Diagnostic Source)

XML

<system.diagnostics> <sharedListeners> <add name="AzureLocalStorage" type="RelyingParty.AzureLocalStorageTraceListener, RelyingParty" /> </sharedListeners> <sources> <source name="Microsoft.IdentityModel" switchValue="Verbose"> <listeners> <add name="AzureLocalStorage" /> </listeners>

Page 46: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

</source> <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing"> <listeners> <add name="AzureLocalStorage" /> </listeners> </source> … </sources> </sharedListeners></system.diagnostics>

10. With this configuration in place, the role will generate trace files, which can be accessed locally when running in the Compute Emulator, but not if running in Azure. To be able to access trace log from Azure, you will setup diagnostics to flush the contents of local stores to Azure Blobs. To do this, add the following line to the OnStart method of the WebRole class.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex02 DiagnosticMonitor Start class code)

C#

public override bool OnStart(){ // To enable the AzureLocalStorageTraceListner, uncomment relevent section in the web.config DiagnosticMonitorConfiguration diagnosticConfig = DiagnosticMonitor.GetDefaultInitialConfiguration(); diagnosticConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); diagnosticConfig.Directories.DataSources.Add(AzureLocalStorageTraceListener.GetLogDirectory());

DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diagnosticConfig);

// For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

return base.OnStart();}

Page 47: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

11. WCF requires some configuration parameter inside its system.serviceModel section to turn on message logging. Add the following diagnostics section to system.serviceModel inside the Web.config file.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex02 System.serviceModel diagnostics section)

XML

<system.serviceModel> <diagnostics> <messageLogging maxMessagesToLog="3000" logEntireMessage="true" logMessagesAtServiceLevel="true" logMalformedMessages="true" logMessagesAtTransportLevel="true" /> </diagnostics> <services> ... </services><system.serviceModel>

Note: Optionaly, you can enable debug information to get more details in case an exception occurs. To do this, add the customErrors mode=”Off” element.

XML

<system.web> <compilation debug="true"> <assemblies> <add assembly="Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> <customErrors mode="Off" /> ...</system.web>

Verification

In order to verify that you have performed every step in the exercise correctly, proceed as follows:

1. With the current configuration in place, the next time you will launch the WCF service you will get a trace log: let’s verify it with a quick run. Make sure that the CloudConfiguration project is the StartUp Project and press Ctrl + F5 to run it without debugging.

2. Right-click the Client project and select Debug | Start new instance.

Page 48: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

3. In the Weather Station client, enter any Zip Code (for example: 1000) and press the Get 3 Days button. You should get the forecast for the following 3 days, while the service should produce a trace of the call.

Note: Thanks to the trace listener, the service saves the traces in a blob of Development storage. Windows Azure does not offer out of the box tools for inspecting the content of Blob Storage. You can easily inspect the content of the Windows Azure storage by mean of its REST API, however teaching you how to use those is out of scope here as this lab is focused on identity. In order to enable you to quickly verify that tracing actually took place, we included in this lab a small utility (BlobsExplorer) which is automatically compiled when you run the SetupLab.cmd script of this Lab. If you are interested in the details of how Windows Azure APIs work feel free to examine the source code of BlobsExplorer, or even better to go though one of the labs of the Windows Azure Training kit.

4. Navigate to the Assets\BlobsExplorer\bin folder inside the Source folder of this Lab and double-click the BlobsExplorer.exe file. The BlobsExplorer UI appears.

5. You will now use BlobsExplorer to download the blobs located in the local storage. Click the Connect Local button (the local storage does not require you to enter account name and key).

Figure 28Connecting to local storage

6. Once the Download button is enabled, update the Blob Container field to wad-tracefiles (this is the container used by the AzureLocalStorageTraceListener class). Then, click Download to get the content of the wad-tracefiles blob container. In the Browser for folder dialog, provide the location where you want to download the content of the blob container and press OK.

Page 49: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 29Downloading the container blob’s content using the BlobsExplorer

Note: If you get an error when you press the Download button saying that the wad-tracefiles container does not exist, try again in a few minutes. Remember that you configured the RelyingParty Role to flush trace logs to the blob storage once per minute.

7. A Windows Explorer window will open, showing the content of the selected folder. To open a trace double-click the *role.svclog file. The .svclog file extension is associated to the Microsoft Service Trace Viewer tool, which will be used by the system to display your trace. Feel free to explore the details of the service call: the UI allows you to browse the various activites (on the left panel) and their associated log entries (on the right).

Page 50: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 30Using the Microsoft Service Trace Listener to check the diagnostic’s logs

8. Close the Weather Station client application.

9. Right-click the Compute Emulator and Storage icon on the Windows’ tray bar and select Show Compute Emulator UI. In the tree at the left panel, right-click the current deployment and select Remove to remove it.

Note: WIF’s extensive diagnostic capabilities are a powerful tool for troubleshooting your claims-nabled WCF services. The ability to examine traces is especially important for cloud deployments, given the current limitations in debugging means. In the task you just completed you learned how to take advantage of this feature: if you want to apply the same skill to on-premises deployments you can follow the same steps, just skip the parts about custom listener and Windows Azure storage configuration.

Task 2 – Adding Load Balancing Support to the WCF Service

In this task you will be to make your service fully load balancing aware. In practical terms, that means handling sessions in such a way that multiple concurrent service instances can gracefully accommodate.

Page 51: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

The task will entail providing some custom classes and diving in the WIF instancing model, but the steps in themselves are very simple.

1. Add a reference to the System.IdentityModel and Microsoft.IdentityModel assemblies on the RelyingParty project. To do this, right-click it in the solution explorer and select Add Reference. In the Add Reference dialog, click the .NET tab, select the System.IdentityModel and Microsoft.IdentityModel assemblies and press OK.

Figure 31Adding a reference to the System.IdentityModel and Microsoft.IdentityModel assemblies

2. Add a class to the RelyingParty project to create a session token handler which uses RSA protection instead of DPAPI. To do this, right-click the RelyingParty project and select Add | Class.

Note: The default encryption strategy followed by WIF for session tokens is to use DPAPI, would create problems when the client interacts with multiple instances: a session token encrypted by a given instance would not be readable by any other. As an alternative you will use the service certificate for securing the session: more about this below. The mechanism that WIF provides for customizing the way in which session tokens are processed consists in providing a custom SessionSecurityTokenHandler class.

Page 52: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

3. In the Add New Item dialog, make sure that the Class template is selected. Set the name of the new class to RsaSessionSecurityTokenHandler and click Add.

Figure 32Adding the RsaSessionSecurityTokenHandler class to the RelyingParty project

4. Replace class content with the following code:

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex02 RsaSessionSecurityTokenHandler class code)

C#

using System;using System.Collections.Generic;using System.IdentityModel.Tokens;using System.Security.Cryptography.X509Certificates;using Microsoft.IdentityModel.Claims;using Microsoft.IdentityModel.Tokens;using Microsoft.IdentityModel.Web;

namespace RelyingParty{ class RsaSessionSecurityTokenHandler : SessionSecurityTokenHandler {

Page 53: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

public RsaSessionSecurityTokenHandler(X509Certificate2 certificate) { List<CookieTransform> transforms = new List<CookieTransform>(); transforms.Add(new DeflateCookieTransform()); transforms.Add(new RsaEncryptionCookieTransform(certificate)); transforms.Add(new RsaSignatureCookieTransform(certificate)); this.SetTransforms(transforms); }

public override ClaimsIdentityCollection ValidateToken(SessionSecurityToken token, string endpointId) { if (token == null) { throw new ArgumentNullException("token"); } if (String.IsNullOrEmpty(endpointId)) { throw new ArgumentException("endpointId"); }

// in active cases where absolute uris are used check the all parts of the token's // endpoint id and this endpoint's id for equality except the port number Uri listenerEndpointId; bool listenerHasUri = Uri.TryCreate(endpointId, UriKind.Absolute, out listenerEndpointId); Uri tokenEndpointId; bool tokenHasUri = Uri.TryCreate(token.EndpointId, UriKind.Absolute, out tokenEndpointId); if (listenerHasUri && tokenHasUri) { if (listenerEndpointId.Scheme != tokenEndpointId.Scheme || listenerEndpointId.DnsSafeHost != tokenEndpointId.DnsSafeHost || listenerEndpointId.AbsolutePath != tokenEndpointId.AbsolutePath) { throw new SecurityTokenValidationException(String.Format("The incoming token for '{0}' is not scoped to the endpoint '{1}'.", tokenEndpointId, listenerEndpointId)); }

Page 54: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

} // in all other cases, fall back to string comparison else if (String.Equals(endpointId, token.EndpointId, StringComparison.Ordinal) == false) { throw new SecurityTokenValidationException(String.Format("The incoming token for '{0}' is not scoped to the endpoint '{1}'.", token.EndpointId, endpointId)); }

return this.ValidateToken(token); } }}

Note: The handler constructor creates a transform pipeline based on RSA transforms tied on the service certificate. The ValidateToken override basically formalize the equivalence modulo port number of all incoming URIs which correspond to the URI of the service, flattening the differences between nodes.

5. Now that we have a good SessionSecurityTokenHandler class, we need to ensure it gets added to the WIF pipeline. To this purpose we will need to add an IServiceBehavior which behaves like ConfigureServiceHostServiceBehavior apart from the custom handler and the tie to the service certificate. Note that this will also give us a chance of introducing the mechanism that handles named WIF config sections. Start by right-clicking the RelyingParty project and selecting Add | Class.

6. In the Add New Item dialog, make sure that the Class template is selected. Set the name to RsaSessionServiceBehavior and then click Add.

7. Replace class content with the following code:

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex02 RsaSessionServiceBehavior class code)

C#

using System;using System.ServiceModel;using System.ServiceModel.Channels;using System.ServiceModel.Description;using Microsoft.IdentityModel.Tokens;using Microsoft.WindowsAzure.ServiceRuntime;

namespace RelyingParty{ class RsaSessionServiceBehavior : IServiceBehavior

Page 55: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

{ public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) { // no op }

public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { // no op }

public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { FederatedServiceCredentials.ConfigureServiceHost(serviceHostBase, RoleEnvironment.GetConfigurationSettingValue("Deployment"));

FederatedServiceCredentials credentials = serviceHostBase.Description.Behaviors.Find<FederatedServiceCredentials>(); credentials.SecurityTokenHandlers.AddOrReplace(new RsaSessionSecurityTokenHandler(serviceHostBase.Credentials.ServiceCertificate.Certificate)); } }}

Note: The class is very straightforward. It calls ConfigureServiceHost by picking the WIF configuration element whose name matches with the content of the string “Deployment”, which represents the target environment. Then it forces the RsaSectionSecurityTokenHandler class in the token handler pipeline, while at the same time initializing it with the service certificate.

8. Implemented the behavior class, we need to provide means to associate it to the service via configuration. To the purpose you will add another class as a behavior extension, associated to the behavior created in the previous step. Right-click the RelyingParty project and select Add | Class. Set the name to RsaSessionServiceBehaviorExtension and then click Add.

9. Replace class content with the following code:

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex02 RsaSessionServiceBehaviorExtension class code)

Page 56: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

C#

using System;using System.ServiceModel.Configuration;

namespace RelyingParty{ public class RsaSessionServiceBehaviorExtension : BehaviorExtensionElement { public override Type BehaviorType { get { return typeof(RsaSessionServiceBehavior); } }

protected override object CreateBehavior() { return new RsaSessionServiceBehavior(); } }}

10. Let’s modify the Web.config file of the RelyingParty project to use all the classes that you have just created. Open the Web.config file inside the RelyingParty project by double-clicking it in the Solution Explorer.

11. Replace the current behavior extension named federatedServiceHostConfiguration for a new one called RsaSessionServiceBehaviorExtension which instantiates the RsaSessionServiceBehaviorExtension class.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex02 RsaSessionServiceBehaviorExtension implementation)

XML

<system.serviceModel> <behaviors> ... </behaviors> <extensions> <behaviorExtensions> <add name="federatedServiceHostConfiguration" type="Microsoft.IdentityModel.Configuration.ConfigureServiceHostBehaviorExtensionElement, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add name="RsaSessionServiceBehaviorExtension" type="RelyingParty.RsaSessionServiceBehaviorExtension, RelyingParty, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />

Page 57: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

</behaviorExtensions> </extensions> <bindings> ... </bindings></system.serviceModel>

12. Update the behavior named RelyingParty.WeatherServiceBehavior, which is using the removed federatedServiceHostConfiguration behavior extension, to use the new RsaSessionServiceBehaviorExtension behavior extension.

XML

<system.servicemodel> <services> ... </services> <behaviors> <serviceBehaviors> <behavior name="RelyingParty.WeatherServiceBehavior"> <federatedServiceHostConfiguration name="RelyingParty.WeatherService" /> <RsaSessionServiceBehaviorExtension /> <serviceMetadata httpsGetEnabled="true" /> ... </behavior> </serviceBehaviors> <behaviors></system.servicemodel>

13. Update the service name inside the microsoft.identityModel section to Development so it matches with the RelyingParty “Deployment” configuration setting value.

XML

<microsoft.identityModel> <service name="Development"> <audienceUris> ... </audienceUris> ... </service></microsoft.identityModel>

14. Press Ctrl + S to save the changes.

Page 58: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

15. Finally, update the RelyingParty role configuration to run two instances when it is deployed so you can verify if load balancing is working. To do this, double-click the RelyingParty node inside the Roles folder of the CloudConfiguration project. In the Configuration tab, set the Instance Count to 2. Press Ctrl + S and close the RelyingParty Role configuration page.

Figure 33Setting 2 instances for the RelyingParty Role

16. To verify that load balancing is working, you will add a Thread.Sleep in the body of the service method providing the forecast: that should give time to a second call to reach the service while the first is still being serviced. Note that this is far from being an exact method. Open the WeatherService.svc.cs file and inside the GetForecast method, uncomment the call to the System.Threading.Thread.Sleep method.

C#

protected WeatherInfo GetForecast(int days, int zipCode){ …

WeatherInfo weatherInfo = new WeatherInfo { Forecast = forecast, Observatory = OperationContext.Current.EndpointDispatcher.ChannelDispatcher.Listener.Uri.AbsoluteUri };

// Uncomment it to verify load balancing System.Threading.Thread.Sleep(3 * 1000);

return weatherInfo;}

Page 59: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Note: The Thread.Sleep here is designed to give you time to invoke the service one second time while the first instance is still busy, hence forcing the second instance to serve the request. Again, this is not guaranteed to work as there is no explicit synchronization: however in the general case it is an easy way of observing the desired behavior.

Verification

In order to verify that you have performed every step in the exercise correctly, proceed as follows:

1. Make sure that the CloudConfiguration project is the StartUp Project and press Ctrl + F5 to run it without debugging.

2. In the Client project, right-click the ServiceReference1 node inside Service References and select Update Service Reference to update the binding used to communicate to the service.

Figure 34Updating Service reference

3. In the Client project, open the app.config file, and delete the CustomBinding_IWeatherService1 endpoint.

XML

<system.serviceModel> <client> <endpoint address="https://127.0.0.1:8443/WeatherService.svc" binding="customBinding" bindingConfiguration="CustomBinding_IWeatherService"

Page 60: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

contract="ServiceReference1.IWeatherService" name="CustomBinding_IWeatherService" /> <endpoint address="https://127.0.0.1:8443/WeatherService.svc" binding="customBinding" bindingConfiguration="CustomBinding_IWeatherService1" contract="ServiceReference1.IWeatherService" name="CustomBinding_IWeatherService1" /> </client><system.serviceModel>

4. Run two instances of the Client project. To do this, right-click the Client project and select Debug | Start New instance (repeat this to create the second instance).

5. Get the forecast for the following three days in both Client instances. Make sure that you press the “Get 3 days” button in the second client instance before receive the answer in the first one.

Figure 35Calling the Service from two clients simultaneously

6. Check the status bar on both clients. You should see that the service endpoints (in this case displaying the internal port numbers associated to the load balancer node running the instance) are different: That implies that the two requests have been handled by different role instances.

Page 61: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 36Retrieving the forecast from different role instances

Note: Once again, what you have learned here can be applied on-premises just as well. The task walked you through the process of adapting the session handling behavior (and the binding) of your service to the case in which multiple instances can be spawn across different machines. As long as your load balancer operates in the same way as the one featured in Windows Azure, the custom SessionSecurityTokenHandler shown here will do its job.

Exercise 3: Deploying the WCF Service to Windows Azure

The Windows Azure Compute Emulator provides a faithful simulation of how its cloud environment works. In the previous exercises, all the code needed to provide the functionalities we wanted has been written, and it will not change regardless of the Windows Azure environment you will deploy your service to. However deploying a service to the cloud does entail knowledge of some specific aspects: resources provisioning, port number handling, alternative configuration settings are all things you need to be aware of in order to successfully roll your service in the cloud. In this last exercise you will learn how to create a hosted service, associate storage to it and take the necessary steps to make your service work in the cloud.

Note: In order to perform this task you need to have an account and an active subscription with Windows Azure.

Page 62: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Note: You require an STS project and appropriate certificates to complete this exercise. If you have not already done so, complete the Getting Started section.

Task 1 – Creating the Hosted Service using the Windows Azure Management Portal

1. Open Microsoft Visual Studio 2010 with administrator privileges. From Start | All Programs | Microsoft Visual Studio 2010, right-click Microsoft Visual Studio 2010 and select Run as administrator.

Note: If you performed all the steps from Exercise 2: Adding Diagnostics and Load Balancing, you can continue using the solution you obtained after completing that exercise and skip to step 4.

2. Open the WIFWCFonWindowsAzure.sln solution file from the \Source\Ex3-DeployingInAzure\Begin folder of this lab.

3. Replace the following placeholders in all solution files. To do this, you can use Visual Studio’s Quick Replace dialog (Edit | Find and Replace | Quick Replace).

◦ Replace the {yourProjectName} placeholder with the name you use for the certificate and the azure project (e.g.: foo)

◦ Replace the {yourCertificateThumbprint} placeholder with the thumbprint of the {yourprojectname}.cloudapp.net certificate you created during the Getting Started: Setting up the Certificates and Local STS section (e.g.: 939026E4657552526FXXXX868DEA80F788991A73)

◦ Replace the {yourMachineName} placeholder with the name of your machine.

Note: You can get more information on how to retrieve the thumbprint of your certificate from the How to: Retrieve the Thumbprint of a Certificate MSDN article.

Page 63: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 37Replacing begin solution placeholders

4. Navigate to http://windows.azure.com using a Web browser and sign in using the Windows Live ID associated with your Windows Azure account.

Figure 38Signing in to the Windows Azure portal

Page 64: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

5. Click on the New Hosted Service button on the ribbon.

Figure 39Creating a new Hosted Service

6. In the Create a new Hosted Service dialog, select the subscription where you wish to create the service from the drop down list labeled Choose a subscription.

Page 65: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 40Choosing your subscription

7. Enter a service name in the textbox labeled Enter a name for your service and choose its URL by entering a prefix in the textbox labeled Enter a URL prefix for your service. This should be {yourprojectname} that you used to create the certificate on the Getting Started: Setting up the Certificates and Local STS section. Windows Azure uses this value to generate the endpoint URLs for the hosted service.

Page 66: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 41Choosing a service name and URL

Note: This is the usual {yourprojectname} that you used for the entire lab. It is the same name you picked as the subject of the X.509 certificate, and the name that will determine the URI of your service in production. If the name you picked is not available, you have to pick a new one: do your best to make it unique, remember that others are going through this lab as well (hence all the obvious names will be already taken). You will have to go back to the former tasks and repeat some steps, using the new name.

Note: The portal ensures that the name is valid by verifying that the name complies with the naming rules and is currently available. A validation error will be shown if you enter name that does not satisfy the rules.

8. Select the option labeled Create or choose an affinity group and then pick Create a new affinity group from the drop down list.

Page 67: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 42Creating a new affinity group

9. In the Create a New Affinity Group dialog, enter wifwazwcf in the Affinity Group Name field, select its Location in the drop down list, and then click OK.

Figure 43Creating a new affinity group

10. Select the Do not Deploy option.

Note: While you can create and deploy your service to Windows Azure in a single operation by completing the Deployment Options section, for this hands-on lab, you will defer the deployment step until the next steps.

11. Click OK to create the hosted service and then wait until the provisioning process completes.

Page 68: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 44Hosted service successfully created

12.

Task 2 – Creating the Storage Account using the Windows Azure Management Portal

In this task you will create a Windows Azure Storage Account to store the diagnostics trace logs, which were configured in the previous exercise.

1. Click Storage Accounts on the left pane. In the Windows Azure ribbon, click New Storage Account.

Figure 45Creating a new storage account

2. In the Create a New Storage Account dialog, pick your subscription in the drop down list labeled Choose a subscription.

Page 69: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 46Choosing a subscription to host the storage account

3. In the textbox labeled Enter a URL, enter the name for your storage account, for example, <yourname>wifwazwcf, where <yourname> is a unique name. Windows Azure uses this value to generate the endpoint URLs for the storage account services.

Figure 47Choosing the URL of the new storage account

Note: The portal ensures that the name is valid by verifying that the name complies with the naming rules and is currently available. A validation error will be shown if you enter a name that does not satisfy the rules.

4. Select the option labeled Create or choose an affinity group and then pick the wifwazwcf affinity group from the drop down list—this is the same affinity group that you defined earlier, when you created the hosted service.

Page 70: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 48Choosing an affinity group

Note: By choosing wifwazwcf affinity group, you ensure that the hosted service is deployed to the same location as the hosted service that you provisioned earlier.

5. Click Create to register your new storage account. Wait until the account provisioning process completes and updates the Storage Accounts tree view. Notice that the Properties pane shows the URL assigned to each service in the storage account. Record the public storage account name—this is the first segment of the URL assigned to your endpoints.

Figure 49Storage account successfully created

Task 3 – Configuring the Web Role for Azure Deployment

In this task you will update the Relying Party Web Role with the necessary configuration to run on Windows Azure.

Page 71: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

1. In the Storage Accounts view of the Windows Azure Management Portal where you created the storage account in the previous task, click the View button next to Primary access key in the Properties pane.

2. In the View Storage Access Keys dialog, click Copy to Clipboard next to the Primary Access Key. You will use this value later on to configure the application.

Figure 50Retrieving the storage access keys

Note: The Primary Access Key and Secondary Access Key both provide a shared secret that you can use to access storage. The secondary key gives the same access as the primary key and is used for backup purposes. You can regenerate each key independently in case either one is compromised.

3. Back to Visual Studio, set the CopyLocal property to True on the Microsoft.IdentityModel assembly reference. To do this, expand the References node of the RelyingParty project, select Microsoft.IdentityModel and press F4 to show its properties. Find the CopyLocal property and set it to true.

Page 72: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 51Setting the CopyLocal property on the reference to the Microsoft.IdentityModel assembly

Note: A Windows Azure application can take advantage of any of the assemblies available in .NET 3.5. Windows Identity Foundation is distributed as a standalone update, hence it is not directly available in Windows Azure. As such, you need to make sure that a copy of the assembly Microsoft.IdentityModel is packaged together with your application bits.

4. In Solution Explorer, double-click the RelyingParty node inside the Roles folder of the CloudConfiguration project.

5. In the Settings tab, update the Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString setting to use the storage account that you created on the previous task. To do this, click the ellipsis (...) button, provide the account name and access key and then press OK.

Page 73: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 52Using Storage account on Windows Azure

6. Update the value of the Deployment setting to Cloud.

Figure 53Settings updated on RelyingParty Role

7. Configure the Web Role to run in LegacyMode. To do this, open the ServiceDefinition.csdef file and delete the <Sites> section.

XML

Page 74: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

<ServiceDefinition name="CloudConfiguration" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"> <WebRole name="RelyingParty"> <Sites> <Site name="Web"> <Bindings> <Binding name="Endpoint1" endpointName="HttpIn" /> <Binding name="Endpoint1" endpointName="HttpsIn" /> </Bindings> </Site> </Sites> <Endpoints> … </Endpoints></ServiceDefinition>

8. Open the Web.config file of the RelyingParty project. Add the following service configuration named Cloud below the Development service inside the microsoft.identityModel section. Remember to update {yourprojectname} label with your Windows Azure Hosted Service name. After that, press Ctrl + S to save the changes and close it.

(Code Snippet – WebServicesAndIdentityInTheCloud Lab - Ex03 Cloud service section)

XML

<microsoft.identityModel> <service name="Development"> ... </service> <service name="Cloud"> <certificateValidation certificateValidationMode="None" /> <audienceUris> <add value="https://{yourprojectname}.cloudapp.net/" /> </audienceUris> <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <trustedIssuers> <add thumbprint="40A1D2622BFBDAC80A38858AD8001E094547369B" name="https://localhost/LocalSTS/Service.svc" /> </trustedIssuers> </issuerNameRegistry> </service></microsoft.identityModel>

Page 75: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Note: As you may recall from earlier steps, the Deployment string is used for switching between alternative WIF configurations from the service’s web.config. The main difference between the Development and Cloud setting sets is that the latter turns off the certificate validation, which would require the bits of the STS signing certificate to be installed in the role certificate store. That is not necessary as we expect the certificate bits to be included in the call itself: storing the certificate thumbprint in the trustedIssuer section is enough for identifying the incoming certificate as belonging to a trusted STS.

9. Go back to the RelyingParty role configuration page. In the Endpoints tab, update the HTTP and HTTPS ports to 80 and 443 respectively.

Figure 54HTTP and HTTPS ports restored to their default values

Note: We don’t need to worry about port collisions any longer: in the cloud we are going to use the regular port 80 for HTTP and 443 for HTTPS, hence we need to adjust the configuration accordingly.

10. Press Ctrl + S to save the changes and close the RelyingParty role configuration page.

Task 4 – Uploading the Certificate and Staging Deployment to Windows Azure

Web roles running on Windows Azure will need access the certificate you configured in previous tasks. In this task you will upload the certificate to Windows Azure and create a new Staging Deployment to run the weather service in Windows Azure.

1. In Visual Studio, create a new package for the CloudConfiguration project. To do this, right-click the CloudConfiguration project and select Publish to generate the package that you will deploy to the cloud in the following steps.

Page 76: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

2. In the Deploy Windows Azure project dialog, make sure to choose Create Services Package Only. This will create the package and open a new window where they are located. You will use these files in the following steps.

Figure 55Creating the service package for deployment

Note: Although the procedure is not shown here, the Publish Cloud Service feature in the Windows Azure Tools enables deployment of your service package directly from Visual Studio. To use this feature, you need to configure a set of credentials that you use to authenticate access to the management service using a self-issued certificate that you upload to the Management Portal.

3. Go back to the browser and the Windows Azure Management Portal.

4. Upload the generated certificate so the WCF service can take advantage of it in the cloud. To do this, click Hosted Services on the left pane and select the Certificates folder inside the hosted service you previously created. Then, click Add Certificate in the ribbon.

Page 77: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 56Adding a new certificate

5. Click the Browse button and select the {yourprojectname}.cloudapp.net.pfx file inside Assets\AzureCertificates folder of this Lab. Type the password you provided when creating the certificates in the passwords fields (if you didn’t provide one, remember that the default password used was “123456”), and press the Create button. Your certificate will be uploaded and you will be able to see it in the Certificates list in the portal page.

Figure 57Choosing a new certificate

Page 78: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 58Certificate in the tree view

Note: The instructions above assume that you used the self-signed certificate generated by the lab script. If you used your own certificate, you must provide a complete .pfx file for it. You can obtain that file by exporting the certificate via Certificates snap-in of the Windows MMC, if the certificate is installed in a local store: don’t forget to export the private key in it, too.

6. In the left menu select Hosted Services, then select the hosted service that you created in the previous steps and then click New Staging Deployment on the ribbon.

Note: A hosted service is a service that runs your code in the Windows Azure environment. It has two separate deployment slots: staging and production. The staging deployment slot allows you to test your service in the Windows Azure environment before you deploy it to production.

Figure 59Hosted service summary page

7. In the Create a new Deployment dialog, to choose a Package location, click Browse Locally, navigate to the folder where Visual Studio generated the package in Steps 1 and 2 and then select the CloudConfiguration.cspkg file.

Page 79: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

8. Now, to choose the Configuration File, click Browse Locally and select ServiceConfiguration.cscfg in the same folder that you used in the previous step.

Note: The .cscfg file contains configuration settings for the application, including the instance count that you will update later in the exercise.

9. Finally, for the Deployment name, enter a label to identify the deployment; for example, use v1.0.

Note: The portal displays the label in its user interface for staging and production, allowing you to identify the version currently deployed in each environment.

Figure 60Configuring the service package deployment

10. Click OK to start the deployment. Notice that the package begins to upload and that the portal shows the status of the deployment to indicate its progress.

Page 80: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 61Uploading a service package to the Windows Azure Platform Management Portal

11. Wait until the deployment process finishes, which may take several minutes. At this point, you have already uploaded the package and it is in a Ready state. Notice that the portal assigned a DNS name to the deployment that includes a unique identifier. Shortly, you will access this URL to test the application and determine whether it operates correctly in the Windows Azure environment, but first you need to configure it. Take note of the ID, you will use it to configure the Client in future steps.

Note: During deployment, Windows Azure analyzes the configuration file and copies the service to the correct number of machines, and starts all the instances. Load balancers, network devices and monitoring are also configured during this time.

Figure 62Package successfully deployed and ready

Page 81: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Verification

In order to verify that you have performed every step in the exercise correctly, proceed as follows:

1. While you wait for the roles to start, get back to Visual Studio.

2. Inside the app.config file of the Client project, update the endpoint address to point to the staging Web Site URL as it is shown below. {stagingDeploymentID} is a unique GUID that Windows Azure generates every time you deploy a package to Staging:

XML

<system.serviceModel> <bindings> ... </bindings> <client> <endpoint address="https://{stagingDeploymentID}.cloudapp.net/WeatherService.svc" binding="customBinding" bindingConfiguration="CustomBinding_IWeatherService" contract="ServiceReference1.IWeatherService" name="CustomBinding_IWeatherService" /> <endpoint address="https://127.0.0.1:8443/WeatherService.svc" binding="customBinding" bindingConfiguration="CustomBinding_IWeatherService" contract="ServiceReference1.IWeatherService" name="CustomBinding_IWeatherService" /> </client></system.serviceModel>

3. Since you are going to execute the client against the staging area of your Hosted Service, the certificate that you uploaded will be not valid (its CN does not match the staging Web Site URL). In order to avoid getting an error, you need to disable the client’s CN check inside the ForecastForm.cs file of the Client project. The necessary code is already in place, just uncomment the callback assignation for ServicePointManager.ServerCertificateValidationCallback.

C#

public partial class ForecastForm : Form{ public ForecastForm() { this.InitializeComponent(); ServicePointManager.ServerCertificateValidationCallback = ValidateCert;

Page 82: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

} private static bool ValidateCert(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { // If running against the staging environment, disable the client’s CN check // Danger Danger: Not Secure return true; }}

Note: By always returning true, the ValidateCert callback disables any form of certificate check. This is done for keeping things simple here, but you should take steps for making sure that such code never goes in production (or for example that, despite of the fact that there is a mismatch with the actual endpoint URI, you check that the certificate is one that you recognize).

4. Go back to the Windows Azure portal, and check if both role instances are running;

Figure 63Role instances running

5. Run two instances of the Client project. To do this, on Visual Studio, right-click the Client project and select Debug | Start New instance (repeat this to create the second instance).

6. In the Weather Station client, enter any Zip Code (for example: 1000) and press the Get 3 Days button in both Client instances. Make sure that you press the “Get 3 days” button in the second client instance before receive the answer in the first one. You should get the forecast for the following 3 days in the different client instances from different roles running on the staging area of your Windows Azure Hosted Service; you can verify this checking their status bar.

Page 83: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

Figure 64Getting the forecast for the following 3 days from the Cloud

7. Get the forecast for the following three and ten days several times providing different Zip codes, in this way, you can check how the different role instances handle the requests.

Summary

Taking advantage of existing identities in new applications is one of the fundamental requirements in today’s distributed systems, and the new wave of cloud based services is no exception.

By completing this hands-on lab you have learned how to:

Use Windows Identity Foundation with WCF services hosted in Windows Azure

Trusting an on-premise STS from a WCF service hosted in Windows Azure

Using WIF & WCF diagnostics features for a WCF service hosted in Windows Azure, taking advantage of blob storage for saving traces

Configure WIF for a WCF service which uses load balancing

Deploy a WCF service secured via WIF to the Windows Azure Platform

Page 84: az12722.vo.msecnd.netaz12722.vo.msecnd.net/identitytrainingcourse1-6/labs/… · Web viewWindows Identity Foundation can simplify access to your Windows Communication Foundation (WCF)

As you have discovered while going through the lab, the claims-based approach to identity enabled by Windows Identity Foundation can be applied with little or no modification to both on-premises and cloud application.

We hope that the programming skills you learned in this and the other identity labs will enable you to write solutions with the confidence that no matter where your application will end up being deployed, you took care of identity in consistent and effective manner.