introduction to the appfabric access...

62
Hands-On Lab Introduction to the AppFabric Access Control Lab version: 2.0.0 Last updated: 11/16/2010

Upload: hoangtram

Post on 07-Sep-2018

255 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Hands-On Lab

Introduction to the AppFabric Access Control

Lab version: 2.0.0 Last updated: 11/16/2010

Page 2: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

CONTENTS

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

EXERCISE 1: USING APPFABRIC ACCESS CONTROL WITH SYMMETRIC KEYS .............................. 6 Task 1 - Exploring the Initial Solution .................................................................................................... 7

Task 2 - Sign Up for AppFabric and Create a Service Namespace......................................................... 9

Task 3 - Set the Service to Accept & Validate AppFabric AC Tokens .................................................. 12

Task 4 - Configuring the AppFabric Access Control Service Namespace to Implement Access Logic

for a Specific Caller .............................................................................................................................. 18

Task 5 - Configuring the Client to Use AppFabric Access Control to Access the Service .................... 31

Exercise 1: Verification ........................................................................................................................ 35

Exercise 1: Summary ............................................................................................................................... 41

EXERCISE 2: USING APP FABRIC ACCESS CONTROL WITH SAML TOKENS .................................. 41 Task 1 - Configure the AppFabric Access Control to Accept Users From a Directory ......................... 43

Task 2 - Create an “ADFSv2 ready” Client ........................................................................................... 52

Exercise 2: Verification ........................................................................................................................ 57

Exercise 2: Summary ............................................................................................................................... 59

SUMMARY .................................................................................................................................................. 59

APPENDIX 1 - USING THE APPFABRIC ACCESS CONTROL MANAGEMENT COMMAND LINE

TOOL .......................................................................................................................................................... 60

Page 3: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Overview

The Windows Azure platform AppFabric Access Control (AC) is a service designed to secure REST web

services. AppFabric AC allows a REST web services to integrate with both simple clients and enterprise

identity technologies using a single code base.

AppFabric AC simplifies access control by enabling Web service providers to offload the cost and

complexity of integrating with various customer identity technologies. Without having to understand

and address each of these technologies, Web services can easily integrate with AppFabric AC using a

simple provisioning process and REST-based management API. Subsequently, the web service can allow

AppFabric AC to serve as the point of integration for service consumers.

This hands-on lab will show you how to take advantage of AppFabric AC to manage access control to

your REST web services.

The lab will explore how to handle access using symmetric keys as credentials, a common practice when

accessing REST APIs. AppFabric AC extends the common scenario with claims-based access capabilities

while maintaining the simplicity of the REST approach.

Furthermore, the lab will demonstrate how you can use AppFabric AC for easily bridging the gap that

traditionally separate the worlds of enterprise services and REST services. You will learn how you can

take advantage of preexisting identity infrastructure, such as Active Directory and ADFSv2, for enabling

enterprise users to instantly access REST web services.

While the samples will be based on .NET and WCF, you will discover that what you will learn about the

use of AppFabric AC can be easily generalized to other platforms.

Objectives

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

Modify your WCF services to take advantage of AppFabric AC for handling access control

Create and manage AppFabric AC Service Namespaces; work with token policies, issuers, scopes

and rules

Invoke REST web services secured by AppFabric AC

Obtain tokens from AppFabric AC via SAML token, and use them to invoke REST web services

System Requirements

You must have the following items to complete this lab:

Page 4: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Microsoft® Windows® Vista SP2 (32-bits or 64-bits) , Microsoft® Windows Server 2008 SP2 (32-

bit or 64-bit), Microsoft® Windows Server 2008 R2, or Microsoft® Windows® 7 RTM (32-bits or

64-bits)

Microsoft® .NET Framework 4

Microsoft® Visual Studio 2010

Microsoft® Windows Identity Foundation Runtime

Microsoft® Windows Identity Foundation SDK

Microsoft® Windows PowerShell

Setup

You must perform the following steps to prepare your computer for this lab.

1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder.

2. Double-click the Dependencies.dep file in this folder to launch the Dependency Checker tool

and install any missing prerequisites. This will also install some code snippets that will be used

across the lab and the localhost certificate used in the second exercise by the local STS.

Note: This process may require elevation. The .dep extension is associated with the

Dependency Checker tool during its installation. For additional information about the setup

procedure and how to install the Dependency Checker tool, refer to the Setup.docx document

in the Assets folder of the training kit.

3. Once closed the code snippets installer, the setup script will proceed with the certificates

installation. If prompted, press Y to continue with the required certificates installation.

Note: If you already have a "localhost" certificate needed by another application, ensure to

make a back up copy of it before continue with the lab's certificates installation.

You can find more information on how to back up a certificate by Exporting the Certificate with

the Private Key on this TechNet link.

Page 5: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 1

Certificates installation finished

4. 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 the SetupLab.cmd

script.

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 AppFabric Access Control with Symmetric Keys

2. Using AppFabric Access Control with SAML Tokens

Page 6: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Note: Each exercise is accompanied by a starting solution. These solutions are missing some code

sections that are completed through each exercise and therefore will not work if running them

directly.

Inside each exercise you will also 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: 50 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.

Exercise 1: Using AppFabric Access

Control with Symmetric Keys

Imagine you run a web site that offers weather forecast reports. Your business model has always been

selling access to your web pages, but your customers are increasingly pressuring you to provide

programmatic access to your forecasts, so that they can be easily integrated in their applications.

You want to satisfy their demands, but you don’t want to get caught in managing multiple relationships

or invest too much energy in handling access control for your API.

Enter the Windows Azure platform AppFabric Access Control (AC). You can outsource to AppFabric AC

most of your access control logic.

AppFabric AC takes care of authenticating your customers for you, issuing them a token that proves

they successfully authenticated and that contains information about their access rights. All you need to

do from your application is verifying the presence of such a token in the call, and enforce the access

control policies that its content entails.

The interaction described above is commonly known as claims-based access, from the fact that the user

attributes included in the token are known as claims. A claim is a statement about a user, issued by an

Page 7: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

authority: if an application receives claims about a user from an authority it trusts, it will assume those

claims to be true and act upon them accordingly. This is a very natural process, which we commonly

experience in real life without even knowing it: every time you show your driver’s license for proving

your age you are using claims.

Claims-based access is common practice for enterprise grade SSO solutions, based on open protocols

such as WS-Federation, SAML and WS-Trust, however it was not available for REST scenarios until now.

AppFabric AC implements a new REST-friendly protocol, called WRAP (Web Resource Authorization

Protocol), which allows you to request tokens from AppFabric AC and use them when invoking REST

services. The tokens you obtain from the AppFabric AC are Simple Web Tokens, or SWT: their compact

format makes them ideal for REST.

This exercise will expand on the weather reporting scenario above, and will walk you through the

process of:

Modifying a WCF service to take advantage of AppFabric AC for handling access control

Create and manage an AppFabric AC Service Namespace; learn how to work with AppFabric AC

resources (token policies, issuers, scopes and rules)

Enable a client to obtain a token from AppFabric AC via symmetric key, and use it for invoking

the WCF service above in a RESTful way

Figure 2

A summary of the scenario enabled by this exercise. The client requests (1) and obtains (2) a SWT

token from the AppFabric AC. The client then uses the SWT to invoke the service (3) and, upon

successful authorization in ACSAuthorizationManager (4), reaches the intended service method.

Task 1 - Exploring the Initial Solution

1. The exercise will modify an existing solution, which already contains a WCF service and its client

ready for you to try. The service is exposed with a REST-friendly binding, and has no

authentication. Let’s take a look at it. Open Microsoft Visual Studio 2010 with administrator

Page 8: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

privileges. From Start | All Programs | Microsoft Visual Studio 2010, right-click on Microsoft

Visual Studio 2010 and select Run as administrator.

2. Open the SimmetricKey.sln solution file located inside the Source\Ex01-

UsingACWithSymmetricKey\Begin folder of this Lab.

3. Right click on the Service project (in Solution Explorer), and select Debug | Start new instance

to run the Service. The web service is a façade to the weather reporting system, and offers two

methods corresponding to two different reports for a given zip code: one that spawns three

days and another that covers ten days.

Figure 3

Weather Service running in console

4. Right click on the Client project (in Solution Explorer), and select Debug | Start new instance to

run the Client. The client will request the three days report and the ten days one after the

other. We have no authentication or authorization mechanism in place, hence both calls will

succeed.

Page 9: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 4

Weather Service Client running

5. Close both applications. Both applications may be closed by pressing Enter on their window.

Task 2 - Sign Up for AppFabric and Create a Service Namespace

In this task, you will create a new AppFabric project.

1. Navigate to http://appfabric.azure.com. You will be prompted for your Windows Live ID

credentials if you are not already signed in.

2. Click the project where you will place the new Service Namespace.

Figure 5

Windows Azure platform AppFabric Portal – Selecting your project

Page 10: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

3. Now you will add a new Service Namespace to your project. A Service Namespace represents a

namespace for the Service Bus and the AppFabric AC. To do this, click the Add Service

Namespace link.

Figure 6

Windows Azure platform AppFabric Portal – Project Summary

4. Type in a name for your Service Namespace, select a Region for your service to run in, and click

the Create button. Make sure to validate the availability of the name first. Service names must

be globally unique as they are in the cloud and accessible by whomever you decide to grant

access.

Please be patient while your service is activated. It can take a few minutes while it is

provisioned.

You may have to refresh the browser to show the service is active.

Page 11: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 7

Windows Azure platform AppFabric Portal – Creating a Service Namespace

Page 12: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 8

Windows Azure platform AppFabric Portal – Project Summary listing the Service Namespaces

5. Click on the Service Namespace just created and review the information like the management

key, the different endpoints to interact with the AppFabric AC, etc.

Figure 9

The Service Namespace details

Note: To sign in at any time, simply navigate to https://appfabric.azure.com, click Sign In, and

provide your Live ID credentials. Clicking the AppFabric tab on the left will list the Services

Projects associated with your account.

Task 3 - Set the Service to Accept & Validate AppFabric AC Tokens

Page 13: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Your service will need few modifications in order to take advantage of AppFabric AC. In summary, you

will need to ensure that before your code is invoked the content of the request is inspected, searching

for a SWT token. Once verified its presence, you will have to check that it is signed with the correct key

(more on this below) and that it contains the claims that your access control policy mandates.

WCF provides various extensibility points you can leverage in order to inspect the request before it

reaches your service code. In this case, an appropriate way of implementing the checks described above

is to derive from the ServiceAuthorizationManager class and embed the necessary logic in it.

Once we have our custom ServiceAuthorizationManager class we can insert it in the WCF pipeline, so

that it will be automatically executed for us at every service invocation.

1. For the purposes of this lab, we are providing a ServiceAuthorizationManager implementation

for you, ready to be imported in the WCF service project. In Solution Explorer, right click on the

Service project and select Add | Existing Item. Browse to the Source\Ex01-

UsingACWithSymmetricKey\Assets folder of this Lab and select ACSAuthorizationManager.cs.

Click OK to close the window.

2. Let’s take a quick peek at the ACSAuthorizationManager class. Double-click on the

ACSAuthorizationManager.cs file you just imported. The class has just two members and a

simple constructor:

C#

public class ACSAuthorizationManager : ServiceAuthorizationManager

{

private TokenValidator validator;

private string requiredClaimType;

public ACSAuthorizationManager(string issuerName, string

trustedAudienceValue, byte[] trustedSigningKey, string requiredClaimType)

{

this.validator = new TokenValidator(issuerName, trustedAudienceValue,

trustedSigningKey);

this.requiredClaimType = requiredClaimType;

}

Note: The TokenValidator class contains the logic that establishes if the incoming token is well

formed and has not been tampered with; the requiredClaimType member represents the

claim we expect to receive, and on which we want to perform our access control checks.

The constructor simply instantiates a new TokenValidator (more on its initialization

parameters below) and assigns the requiredClaimtype member.

The key method of a ServiceAuthorizationManager is CheckAccessCore. Let’s examine our

override:

C#

Page 14: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

protected override bool CheckAccessCore(OperationContext operationContext)

{

// get the authorization header

string authorizationHeader =

WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Authoriz

ation];

if (string.IsNullOrEmpty(authorizationHeader))

{

SetUnauthorizedResponse();

return false;

}

// check that it starts with 'WRAP'

if (!authorizationHeader.StartsWith("WRAP "))

{

SetUnauthorizedResponse();

return false;

}

string[] nameValuePair = authorizationHeader.Substring("WRAP

".Length).Split(new char[] { '=' }, 2);

if (nameValuePair.Length != 2 ||

nameValuePair[0] != "access_token" ||

!nameValuePair[1].StartsWith("\"") ||

!nameValuePair[1].EndsWith("\""))

{

SetUnauthorizedResponse();

return false;

}

// trim the leading and trailing double-quotes

string token = nameValuePair[1].Substring(1, nameValuePair[1].Length - 2);

// validate the token

if (!this.validator.Validate(token))

{

SetUnauthorizedResponse();

return false;

}

// check for an action claim and get the value

Dictionary<string, string> claims = this.validator.GetNameValues(token);

string actionClaimValue;

if (!claims.TryGetValue(this.requiredClaimType, out actionClaimValue))

{

SetUnauthorizedResponse();

Page 15: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

return false;

}

// check for the correct action claim value

string requiredActionClaimValue =

WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RelativePathSegme

nts.First();

string[] actions = actionClaimValue.Split(',');

if (!actions.Any(a => requiredActionClaimValue.Equals( a,

StringComparison.OrdinalIgnoreCase)))

{

SetUnauthorizedResponse();

return false;

}

return true;

}

private static void SetUnauthorizedResponse()

{

WebOperationContext.Current.OutgoingResponse.StatusCode =

HttpStatusCode.Unauthorized;

WebOperationContext.Current.OutgoingRequest.Headers.Add("WWW-

Authenticate", "WRAP");

}

Without going too much into details, the method:

◦ Inspects the Authorization HTTP header and verifies it is complying with the WRAP

protocol

◦ Retrieves the token from the header and validates it (more on this later)

◦ If the token resulted valid, it retrieves the action corresponding to the method currently

being called. It then queries the token to retrieve the values of the claim type indicated

by requiredClaimType. If among those values there is the action of the current method,

the call is authorized and CheckAccessCore returns True

◦ If any of the checks above fail, the method prepares the response to return a

401:Unauthorized code to the caller and exits by returning False

3. As we have seen above, ACSAuthorizationManager relies on the helper class TokenValidator

for checking the validity of the incoming token. Also in this case we are providing an

implementation for you. In Solution Explorer, right click on the Service project and select Add |

Existing Item. Browse to Ex01-UsingACWithSymmetricKey\Assets inside the Source folder of

this Lab and select TokenValidator.cs. Click OK to close the window.

Page 16: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

4. Open TokenValidator.cs by double-clicking on it in Visual Studio. The class TokenValidator

contains boilerplate code for performing verifications on the incoming token: let’s take a look at

its main parts.

The constructor is truly straightforward:

C#

public TokenValidator(string issuerName, string trustedAudienceValue, byte[]

trustedSigningKey)

{

this.trustedSigningKey = trustedSigningKey;

this.trustedTokenIssuer = issuerName.ToLowerInvariant();

this.trustedAudienceValue = new Uri(trustedAudienceValue);

}

Let’s examine the meaning of the parameters it requires:

◦ trustedSigningKey represents the key you expect the incoming token to be signed with.

It is associated to the authority you trust, in this case an AppFabric AC service endpoint.

◦ trustedTokenIssuer represents the name of your AppFabric AC Service Namespace. We

will see its meaning in a later task, for now just consider it as a container for the

authorization logic stored in AppFabric AC, and a part of the address to which you will

send requests for tokens.

◦ trustedAudienceValue is the intended destination of the call, the address to which we

expect the token to be issued for. An unexpected value in this parameter would indicate

that the token may have been hijacked from another call

The core method of TokenValidator is Validate:

C#

public bool Validate(string token)

{

if (!this.IsHMACValid(token, this.trustedSigningKey))

{

return false;

}

if (this.IsExpired(token))

{

return false;

}

if (!this.IsIssuerTrusted(token))

{

return false;

}

Page 17: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

if (!this.IsAudienceTrusted(token))

{

return false;

}

return true;

}

The method uses various utility functions for verifying various characteristics of the token. Is the

signature valid? Is the token past its expiration? Is it addressed to its intended audience? And so

on.

If you want to understand more of the SWT token format, you can examine the implementation

of those utility functions: you will discover that the format is extremely simple, and so is the

code required to process it.

5. Our service project now contains all the helper code we need for using AppFabric AC. Let's

modify the service initialization code to include the ACSAuthorizationManager class as

appropriate. First, we'll need to add a few parameters that we will have to pass down to

ACSAuthorizationManager at initialization time. In Solution Explorer, Service project, double

click on the Program.cs file, and add the following code right after the Program class

declaration. We described the meaning of all those parameters in the former steps. The Service

Namespace and TokenPolicyKey values will be obtained from our AppFabric AC settings, and we

will fill them in after we will have configured our service namespace in the next task.

(Code Snippet – Introduction to AppFabric AC Lab - Ex01 Service Constants)

C#

public class Program

{

private const string ServiceNamespace = "{insert service namespace

here}";

private const string TokenPolicyKey = "{insert token policy key

here}";

private const string Audience = "http://localhost/weatherforecast";

private const string RequiredClaimType = "action";

private const string IssuerName =

"https://{0}.accesscontrol.windows.net/";

public static void Main(string[] args)

6. Update the ServiceNamespace value with the Service Namespace you chose in task 2, step 4.

C#

private const string ServiceNamespace = "{insert service namespace here}";

Page 18: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

7. Finally, we will modify the service host to use ACSAuthorizationManager. To do that, in

Program.cs add the following code right before the host.Open() invocation:

(Code Snippet – Introduction to AppFabric AC Lab - Ex01 AppFabric AC Instantiation)

C#

host.AddServiceEndpoint(typeof(IWeatherForecast), binding, new

Uri("http://localhost/weatherforecast"));

host.Authorization.ServiceAuthorizationManager = new ACSAuthorizationManager(

string.Format(IssuerName, ServiceNamespace),

Audience,

Convert.FromBase64String(TokenPolicyKey),

RequiredClaimType);

host.Open()

That’s it. Our service code is now ready to handle requests secured via AppFabric AC: we no

longer need to worry about handling relationships, credentials or access policies from within our

service.

All that’s left for us is telling AppFabric AC who should have access to our service, and in what

terms. In order to do that, we will use the AppFabric AC Management Service to modify our

Service Namespace according to our needs.

Task 4 - Configuring the AppFabric Access Control Service Namespace to Implement Access Logic for a

Specific Caller

The way in which you configure your AppFabric AC Service Namespace is via the AppFabric AC

management service. You can use the management service for creating, modifying and deleting the

resources that are necessary for driving the token issuing behavior you want to obtain. The

management service is REST-based and accepts calls secured via your service namespace managed key,

which we have obtained in task 2.

The SDK of AppFabric AC provides a sample application called AppFabric Access Control Management

Browser, which allows you to interact with the AppFabric AC management service using a GUI. A copy of

this tool has been provided within this lab inside the Source\Assets folder.

In this task we will use the AppFabric AC Management Browser for setting up our Service Namespace so

that it will grant one customer selective access to our weatherreport service. Namely, we will grant to

our partner access to the Get3DaysForecast method but we will block calls to any other method. As we

go through the steps, we will explain the purpose of the resources we will be creating and the role they

play in implementing our access control logic.

Page 19: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

At the end of the task our AppFabric AC Service Namespace will be ready to issue tokens expressing our

authorization logic, and we will have generated the symmetric key that our customer will use for

obtaining tokens from AppFabric AC and invoke our service.

1. The first resource we need to create is a Token Policy. To do this, browse to

Assets\AcmBrowser inside the Source folder of this Lab and double click the AcmBrowser.exe

file.

Figure 10

AppFabric AC Management Browser

2. To start working type the Service Namespace you want to manage, along with its Management

Key. Both parameters can be found on the details of the Service Namespace in the AppFabric

portal.

Page 20: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 11

Loading the Service Namespace configuration from the Cloud

3. You'll now create the Token Policy that represents a set of parameters that AppFabric AC will

use for issuing tokens. To create a new Token Policy right click on the Token Policy node in the

Resources tree view, and select Create.

Page 21: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 12

Creating a Token Policy

4. This will open a dialog to complete the Token Policy details. Enter the following values and click

OK when you finish.

◦ Name: weatherforecast

◦ Token Lifetime: 28800 (8 hours)

◦ Signing Key: click Generate to generate a random signing key for the tokens emitted by

AppFabric AC.

Page 22: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 13

Completing the values for a Token Policy

Note: A token policy represents a set of parameters that AppFabric AC will use for issuing a

token. A service namespace can contain multiple token policies.

A token policy is defined by four properties:

Id: unique identifier which characterizes the resource. Every AppFabric AC resource has one: it

can be used for constructing the resource URI. The Id is assigned by the service at creation

time, hence we don’t need to specify it.

DisplayName: a mnemonic moniker assigned to the resource. As for Id, ever AppFabric AC

resource has one: however it does not have to be unique.

DefaultTokenLifetimeInSeconds: The number of seconds that the token will be valid for.

SigningKey: The signing key AppFabric AC uses to sign tokens issued with this token policy.

AppFabric AC sign tokens via HMACSHA256 algorithm, using 32 byte keys. The AppFabric AC

Management Browser gives you the choice of either specify a key value, or generate one.

Page 23: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

5. Next, we need to create an AppFabric AC Scope that will gather all our access control logic that

will have to be triggered when a request is sent to the URI of our weather forecast REST service.

To do that, right click on the Scopes node on the Resources tree view and select Create.

Figure 14

Creating a Scope

6. This will open a dialog to complete the Scope details. Enter the following values and click OK

when you finish.

◦ Display Name: weatherforecast

◦ Applies To: http://localhost/weatherforecast

◦ Token Policy: select weatherforecast from the dropdown list

Page 24: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 15

Completing the values for a Scope

Note: A scope is, as mentioned, the mechanism that AppFabric AC uses for associating settings

to a given resource URI. As for the token policies, a service namespace can include multiple

scopes. Besides the Id and DisplayName properties, common to every AppFabric AC resource,

a scope is defined by:

AppliesTo: The URI of the resource for which we want to specify access control logic.

TokenPolicyId: The tokens issued for accessing the resource specified in AppliesTo will follow

the setting specified by the token policy represented by TokenPolicyId.

7. The time has come to define the intended audience of our service: we need to tell AppFabric AC

how to recognize if a call comes from a legitimate source. To do this, right click on the Issuers

node in the Resources tree view and select Create.

Page 25: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 16

Creating an Issuer

8. This will open a dialog to complete the Issuer details. Enter the following values and click OK

when you finish.

◦ Display Name: weatherforecastclient

◦ Algorithm: leave the default selection (Symmetric256BitKey)

◦ Issuer Name: weatherforecastclient

◦ Current Key: click Generate button to generate a random one

◦ Previous Key: click Generate button to generate a random one

Page 26: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 17

Completing the Issuer details

Note: An issuer in AppFabric AC describes the cryptographic material that a caller will use

when requesting a token. It will be used for authenticating the call and deciding which

authorization logic should be applied for the specific service consumer.

The defining properties of an issuer in AppFabric AC are:

IssuerName: The name that the issuer will use for identifying itself in the token request. Note

that this is different from the Name property, which is just a friendly name and never leaves

the boundaries of the management service.

Algorithm: This parameters determine which kind of signature AppFabric AC should expect for

tokens coming from this issuer. The possible values are Symmetrick256Key, the default, X509

and FedMetadata. We will discuss the FedMetadata option more in depth in the next exercise.

CurrentKey: The key that AppFabric AC will need to use for verifying the signature of tokens

coming from this issuer. If the algorithm is Symmetric256Key this will be a 32-byte SHA-256

key. If algorithm is X509, this will be a base64 encoded certificate.

Page 27: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

In our specific example we will generate the keys using the tool. This will be the key that we

will have to distribute to our intended service consumer, so that it will be able to use it for

requesting tokens.

9. We finally have all the settings in place for describing our desired access control logic. In this

exercise we will do something extremely simple, we will grant the right to call our

Get3DaysForecast method to the issuer we previously defined and we will exclude everybody

else. In practice, this means creating an AppFabric AC Rule that allows access to the

Get3DaysForecast operation for any client associated to the issuer key previously created. To

do this, expand the Scopes node, expand the scope to which you want to create the new rule,

right click on the Rules child node and select Create.

Figure 18

Creating a new Rule

10. In the dialog, complete the fields with the following information:

◦ Name: client3days (this is just a label to identify this rule later)

Page 28: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

◦ Type: Simple (the Simple rule type operates by matching an input claim and build a new

output whereas the PassThrough rule type copies the input claim value of the matching

input claim)

Input Claim

Claim Issuer: weatherforecastclient (the issuer we created on step 8)

Claim Type: Issuer (this is a reserved claim that is always generated by AppFabric

AC. This value is case sensitive)

Value: weatherforecastclient (this is the name of the issuer)

Output Claim

Type: action (the claim type that the application will accept)

Value: Get3DaysForecast (in this case the value the REST service is expecting to

allow access to a specific method)

Figure 19

Completing the Rule details

Page 29: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Note: A rule describes the logic that should be executed when a request from a certain issuer

to obtain a token for a certain resource is received. Given an incoming claim type and value, it

specifies which claim type and value should be included in the token the AppFabric AC will

issue (according to a given token policy). The value of the outgoing claim will contain an

indication if the service should allow access to the resource being requested (if access is

denied, there won't be an outgoing claim).

11. After clicking OK, a new rule will be created (but not yet saved). You may review the rule by

browsing through the Resources tree view, as shown below.

Figure 20

Reviewing the newly created Rule in the Resources tree

12. Finally, to apply the changes we just made, click on the Save to Cloud toolbar button, as shown

below. This will connect to the AppFabric AC Management Service and create the Token Policy,

Scope, Issuer and Rules we just created.

Page 30: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 21

Saving the changes to the Cloud

Note: The AppFabric AC Management Browser included in the current SDK does not allow you

to modify resources after creation. As a result, in order to apply the changes we made we need

to delete all the existing resources in the namespace and re-apply to the cloud the settings

described by the current state of the AppFabric AC Management Browser.

13. The AppFabric AC is now ready to handle requests for our service: we just need to make sure

that our service will recognize tokens issued according to the token policy we just defined. To

do this, first get the token policy key from the AppFabric AC Management Browser. Expand the

Token Policies node and click on weatherforecast. Select the Signing Key and copy it to the

clipboard.

Page 31: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 22

Get the token policy key

14. Paste the token policy key you just copied in the clipboard into the TokenPolicyKey constant on

Service\Program.cs file.

C#

private const string TokenPolicyKey = "{insert token policy key here}";

We are all set for starting to receive calls. All we need is provisioning our customer with the

issuer key we generated in step 7; that value and few lines of code for handling AppFabric AC

token requests is all our customer needs for gaining access to our service.

Task 5 - Configuring the Client to Use AppFabric Access Control to Access the Service

Let’s modify our initial client with the code that is necessary for requesting a token from AppFabric AC

and using the resulting token for securing the call to the service.

1. In Solution Explorer, Client project, double click on the Program.cs file. Add the following using

directives at the beginning of the file for the code we'll be adding later.

Page 32: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

(Code Snippet – Introduction to AppFabric AC Lab - Ex01 Client Usings)

C#

namespace Client

{

using System;

using System.Net;

using System.ServiceModel;

using System.ServiceModel.Security;

using System.ServiceModel.Web;

using System.Collections.Specialized;

using System.Linq;

using System.Text;

using System.Web;

using System.IO;

public class Program

2. In Program.cs, insert the following code right after the Program class declaration. . We'll update

the Service Name and Issuer Key in the next task.

(Code Snippet – Introduction to AppFabric AC Lab - Ex01 Client Parameters)

C#

public class Program

{

private const string ServiceNamespace = "{insert service namespace here}";

private const string IssuerName = "weatherforecastclient";

private const string IssuerKey = "{insert issuer key here}";

private const string AcsHostName = "accesscontrol.windows.net";

public static void Main(string[] args)

{

3. Change the client to use the issuer key generated in the previous task. To do this, first get the

issuer key from AppFabric AC Management Browser. To get the issuer key, expand the Issuers

node and click on weatherforecastclient. Select the Current Key and copy it to the clipboard.

Page 33: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 23

Get the issuer key

4. Paste the issuer key you just copied in the clipboard into the IssuerKey constant on Client

\Program.cs file.

C#

private const string IssuerKey = "{insert issuer key here}";

5. Update the service name (the one you’ve got in Task 2, step 4) used in the client

Client\Program.cs file. To do this, replace the ServiceNamespace constant in the code.

C#

private const string ServiceNamespace = "{insert service namespace here}";

6. The first thing we need to do in our code is requesting a token from AppFabric AC. Add the

following code at the end of Program class.

(Code Snippet – Introduction to AppFabric AC Lab - Ex01 GetACSToken Method)

C#

Page 34: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

...

private static string GetACSToken()

{

// request a token from AppFabric AC

WebClient client = new WebClient();

client.BaseAddress = string.Format("https://{0}.{1}",

ServiceNamespace, AcsHostName);

NameValueCollection values = new NameValueCollection();

values.Add("wrap_name", IssuerName);

values.Add("wrap_password", IssuerKey);

values.Add("wrap_scope", "http://localhost/weatherforecast");

byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST",

values);

string response = Encoding.UTF8.GetString(responseBytes);

return response

.Split('&')

.Single(value => value.StartsWith("wrap_access_token=",

StringComparison.OrdinalIgnoreCase))

.Split('=')[1];

}

}

}

Note: Requesting a token from AppFabric AC via WRAP protocol and SWT token format is

extremely simple: we just POST a name/value collection to our service namespace, containing

the URI of the service we want to invoke and the issuer credentials we configured.

7. At the beginning of the Main method add code to retrieve an AppFabric AC token using the

GetACSToken method we just added. Insert the following code at the beginning of Main():

(Code Snippet – Introduction to AppFabric AC Lab - Ex01 GetACSToken invocation)

C#

public static void Main(string[] args)

{

string acsToken;

try

{

acsToken = GetACSToken();

}

catch (WebException ex)

{

Console.ForegroundColor = ConsoleColor.Red;

if (ex.Response != null)

Page 35: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

{

Stream exception = ex.Response.GetResponseStream();

StreamReader reader = new StreamReader(exception);

Console.WriteLine(reader.ReadToEnd());

}

else

{

Console.WriteLine(ex.Message);

}

Console.ReadLine();

return;

}

...

8. To invoke the service using the token we received from AppFabric AC it's necessary to add it in

the "authorization" HTTP header (there are other ways of doing it, which we won’t explore

here: please refer to the online documentation of AppFabric AC). To do that, insert the

following code right after the OperationContextScope:

(Code Snippet – Introduction to AppFabric AC Lab - Ex01 Client authorization header)

C#

using (new OperationContextScope(proxy as IContextChannel))

{

string authHeaderValue = string.Format("WRAP access_token=\"{0}\"",

HttpUtility.UrlDecode(acsToken));

WebOperationContext.Current.OutgoingRequest.Headers.Add("authorization",

authHeaderValue);

// call the service and get a response

This concludes the steps that a client needs to perform in order to be able to invoke REST

services protected by AppFabric AC. In the next task we will verify how our new service works.

Exercise 1: Verification

In order to verify that you have correctly performed all steps in exercise one, proceed as follows:

1. Right click on the Service project (in Solution Explorer), and select Debug | Start new instance

to run the Service.

Page 36: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 24

Service console

2. Right click on the Client project (in Solution Explorer), and select Debug | Start new instance to

run the Client.

Figure 25

Client console showing the 3 days forecast but not the 10 days forecast because the user don’t

have access to that.

3. Verify that the 3 days forecast is retrieved by looking at the console output. You'll also notice

that the console displays an error on the following line. This is exactly in line with expectations:

Page 37: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

our rule granted this client access only to the Get3DaysForecast method, hence the attempt to

access Get10DaysForecast was blocked with a (401) Unauthorized return code.

4. Let’s see how easy it is to manage access control now that AppFabric AC takes care of it. We will

add an AppFabric AC Rule that allows access to the Get10DaysForecast operation. To do this, go

to the AppFabric AC Management Browser and expand Scopes | weatherforecast | Rules. Right

click on Rules and click on Create.

Figure 26

Create a new rule.

5. In the dialog that opens, complete the fields with the following information:

a. Name: client10days

b. Type: Simple

c. Input Claim

i. Issuer: weatherforecastclient

ii. Type: Issuer (this value is case sensitive)

iii. Value: weatherforecastclient

Page 38: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

d. Output Claim

i. Type: action

ii. Value: Get10DaysForecast

Figure 27

Completing the Rule details to allow access to Get10DaysForecast operation

6. Click on Clear Service Namespace in Cloud. This will remove all existing resources in AppFabric

AC. Press Yes on the confirm dialog.

Note: The AppFabric AC Management Browser included in the current SDK does not allow you

to modify resources after creation. As a result, in order to apply the changes we made we need

to delete all the existing resources in the namespace and re-apply to the cloud the settings

described by the current state of the AppFabric AC Management Browser.

Page 39: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 28

Clearing the service namespace before saving.

7. Once the AppFabric AC Management Browser finished clearing the service namespace, press on

Save to Cloud button.

Page 40: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 29

Saving the service namespace.

8. Now that the new rule is in place, the client should be able to access both forecasts. Right click

on the Client project (in Solution Explorer), and select Debug | Start new instance to run the

Client.

Page 41: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 30

Client console showing both forecasts

Exercise 1: Summary

In this exercise you learned how to modify your existing WCF REST services to rely on AppFabric AC for

authentication and authorization, and walked through the changes that enable client applications to

invoke services protected by AppFabric AC.

You have been introduced to the main AppFabric AC resources and their basic properties, and you have

learned how to work with them for implementing simple access control logic.

Finally, you experienced first-hand how easy it is to change access control settings for your REST services

without having to touch the code of the service itself.

This exercise barely scratched the surface of what can be achieved with AppFabric AC and claims-based

access: in the next exercise we will go a bit deeper and demonstrate slightly more sophisticated rules.

Exercise 2: Using App Fabric Access

Control with SAML Tokens

Page 42: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

In the first exercise we have shown how you can use AppFabric AC for enabling claims-based access

without requiring anything more than the classic tools you’d use in REST API integration scenarios. In

this exercise we will explore a more advanced case.

Let’s say you want to make your REST service available to the users stored in a business repository such

as Active Directory: this is a common requirement, but one that traditional approaches to REST security

fail to address. AppFabric AC solves this situation: if that repository has an ADFSv2 instance associated

to it, AppFabric AC can easily leverage it for enabling AD accounts to securely invoke REST services.

The idea behind the scenario is very simple. The ADFSv2 instance can be a trusted issuer for your

AppFabric AC Service Namespace, much like the issuer we defined in task 4 of the former exercise: the

only difference is that it will issue tokens in SAML format instead of SWT. A client will request AppFabric

AC tokens by sending one of such SAML tokens: the claim content of the SAML token is what the

AppFabric AC will use for determining the content of the token it will issue to the requestor. From now

on, it will be business as usual: the service will receive an SWT token, precisely as in shown in the first

exercise, and will use it for determining access.

In this exercise you will learn how to modify a client in order to obtain a SAML token from an ADFSv2

instance and use it for requesting a token from AppFabric AC. You will also see how you can leverage the

ADFSv2 metadata documents for automating part of the settings that the management service needs

for configuring access. Finally, you will see how claims allow you to leverage user attributes such as

group memberships for creating sophisticated access logic to your REST web service.

Page 43: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 31

A summary of the scenario enabled by this exercise. The client requests (1) and obtains (2) a SAML token

from the ADFSv2 instance; it uses the same SAML token for requesting a token from AppFabric AC (3)

and obtains a SWT token in return (4). The client then uses the SWT to invoke the service (5) and, upon

successful authorization in ACSAuthorizationManager (6), reaches the intended service method.

Task 1 - Configure the AppFabric Access Control to Accept Users From a Directory

In this task we are going to build up on the AppFabric AC service we have built in exercise 1.

We already have a service namespace and a token policy that our service is configured to trust: what we

need to do is define a new issuer, which will represent the ADFSv2 authority, and create the appropriate

rules that will process the incoming SAML token and produce access decisions.

1. The exercise will modify an existing solution, which already contains a WCF service and its client

ready for you to try. Open Microsoft Visual Studio 2010 with administrator privileges. From

Start | All Programs | Microsoft Visual Studio 2010, right-click on Microsoft Visual Studio 2010

and select Run as administrator.

2. Open the ACSWithSAML.sln solution file located in the Source\Ex02-

UsingACWithSAMLTokens\Begin folder of this Lab.

3. In Solution Explorer, Service project, double click on the Program.cs file. Update the

ServiceNamespace value with the service namespace you chose in the first exercise, task 2, step

4.

C#

private const string ServiceNamespace = "{insert service namespace here}";

4. We'll now need to update our service to recognize tokens issued according to the token policy

we defined on the first exercise. To do this, first get the token policy key from AppFabric AC

Management Browser. Navigate to Assets\AcmBrowser inside the Source folder of this Lab and

double click on AcmBrowser.exe.

Page 44: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 32

AppFabric AC Management Browser

5. To start working type the Service Namespace you want to manage, along with its Management

Key. Both parameters can be found on the details of the Service Namespace in the AppFabric

portal.

Page 45: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 33

Loading the Service Namespace configuration from the Cloud

6. Expand the Token Policies node and click on weatherforecast. Select the Signing Key and copy

it to the clipboard.

Page 46: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 34

Get the token policy key

7. Paste the token policy key you just copied in the clipboard into the TokenPolicyKey constant on

Service\Program.cs file.

C#

private const string TokenPolicyKey = "{insert token policy key here}";

8. Run the local STS that will simulate an ADFSv2. To do this, open a command prompt as

administrator and change the directory to the Source\Ex02-UsingACWithSAMLTokens\Assets

folder inside this Lab, and type LocalSTS.exe and keep it open for the rest of the exercise.

Page 47: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 35

Running LocalSTS tool

Note: ADFSv2 is a server product with specific infrastructure requirements, among which

there is Active Directory. Rather than forcing you to download, configure and manage a large

virtual machine file, in this hands-on lab we will simulate an ADFSv2 instance with a custom

STS written using Windows Identity Foundation. From the developer perspective the

experience is absolutely equivalent: the instructions we give here would apply without any

modification if the STS would be exposed by an ADFSv2 instance.

9. Now you will configure our STS as a trusted issuer on AppFabric AC. The AppFabric AC

Management Browser is able to automate a large part of the operation, simply by taking

advantage of the metadata exposed by the STS itself. To do this, switch back to AppFabric AC

Management Browser and right click on Issuers and click on Create.

Page 48: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 36

Creating a new issuer

10. This will open a dialog to complete the Issuer details. Enter the following values and click OK

when you finish.

◦ Display Name: localSTS

◦ Algorithm: FedMetadata

◦ Endpoint URI: https://localhost/localsts/FederationMetadata/2007-

06/FederationMetadata.xml

Page 49: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 37

Entering the FederationMetadata endpoint for the new SAML issuer

11. Now that you created the issuer you want to create rules associated to that issuer. Your new

access control rule will be based on the content of the SAML token coming from the ADFSv2

instance of your trusted partner. Let’s say that you know that employees in the security group

“Pilots” are meant to have access to the getforecast3days method: all you need to do is creating

a rule that issues an action claim with value “Get3DaysForecast” whenever an incoming claim of

type http://schemas.xmlsoap.org/claims/Group and value “Pilots” is received from this issuer.

To create such rule, expand Scopes | weatherforecast, right click on Rules and click on Create.

Page 50: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 38

Creating a new rule for the SAML issuer

12. In the dialog, complete the fields with the following information:

◦ Name: pilots3days

◦ Type: Simple

Input Claim

Issuer: localSTS (the issuer created in the previous step)

Type: http://schemas.xmlsoap.org/claims/Group

Value: Pilots

Output Claim

Type: action

Value: Get3DaysForecast

Page 51: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 39

Creating a new rule for the SAML issuer

13. To save the changes, press Clear Service Namespace in Cloud and then Save to Cloud buttons.

Page 52: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 40

Clearing and saving the namespace

This is all you need to do for configuring your AppFabric AC Service Namespace. Next, we will

explore the changes that the client must introduce for successfully obtaining a SWT token from

AppFabric AC when presenting a SAML token: once that happens, it is business as usual for

everything else.

Task 2 - Create an “ADFSv2 ready” Client

In this task you will add to the client the code that retrieves a SAML token from the local STS, send it to

AppFabric AC, get a SWT token back and finally call the service transmitting the SWT token in an HTTP

header.

1. In Solution Explorer, right click on the Client project and select Add Reference. Select the

Microsoft.IdentityModel assembly and click OK. This will add the required assembly reference

to use Windows Identity Foundation classes.

Page 53: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 41

Adding a reference to Microsoft.IdentityModel

2. In Solution Explorer, Client project, double click on the Program.cs file. Add the following using

directives at the beginning of the file for the code we'll be adding later.

(Code Snippet – Introduction to AppFabric AC Lab - Ex02 Client Usings)

C#

namespace Client

{

using System;

using System.Net;

using System.ServiceModel;

using System.ServiceModel.Security;

using System.ServiceModel.Web;

using System.Collections.Specialized;

using System.IdentityModel.Tokens;

using System.Linq;

using System.Text;

using System.Web;

using Microsoft.IdentityModel.Protocols.WSTrust;

using Microsoft.IdentityModel.Protocols.WSTrust.Bindings;

using System.IO;

Page 54: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

The last two namespaces are from Windows Identity Foundation: we will use the classes found

there for retrieving the SAML token from the local STS.

3. Add the following constants in the body of the Program class.

(Code Snippet – Introduction to AppFabric AC Lab - Ex02 Client constants)

C#

public class Program

{

private const string ServiceNamespace = "{insert service namespace here}";

private const string AcsHostName = "accesscontrol.windows.net";

private const string StsBaseAddress = "localhost/localsts";

private const string StsPath = "Trust/13/UserName";

public static void Main(string[] args)

4. Update the Service Namespace (the one you entered in Task 2 of the first exercise, step 4) used

in the client Client\Program.cs file. To do this, replace the ServiceNamespace constant in the

code.

C#

private const string ServiceNamespace = "{insert service namespace here}";

5. Add the following lines of code to call the local STS and receive a SAML token in return. The

SAML token will then be sent to AppFabric AC to be exchanged with a SWT token.

Note: The order of these instructions aim at helping you understand what it takes for a client

to be able to use AppFabric AC, hence it follows a top-down approach. The code won’t compile

at this point, but it eventually will, once you will have followed the instructions in the next 3

steps.

(Code Snippet – Introduction to AppFabric AC Lab - Ex02 Client call STS)

C#

public static void Main(string[] args)

{

string stsAddress = string.Format("https://{0}/{1}", StsBaseAddress,

StsPath);

string acsSTSAddress = string.Format("https://{0}.{1}/WRAPv0.9",

ServiceNamespace, AcsHostName);

string samlAssertion = GetSamlAssertion(stsAddress, acsSTSAddress);

string acsToken;

try

Page 55: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

{

acsToken = GetACSToken(samlAssertion);

}

catch (WebException ex)

{

Console.ForegroundColor = ConsoleColor.Red;

if (ex.Response != null)

{

Stream exception = ex.Response.GetResponseStream();

StreamReader reader = new StreamReader(exception);

Console.WriteLine(reader.ReadToEnd());

}

else

{

Console.WriteLine(ex.Message);

}

Console.ReadLine();

return;

}

6. Add the definition of the GetSamlAssertion method, which gets a token from the local STS. To

do that, copy the following code at the end of the Program class.

(Code Snippet – Introduction to AppFabric AC Lab - Ex02 GetSamlAssertion Method)

C#

...

public static void Main(string[] args)

{

...

}

private static string GetSamlAssertion(string stsAddress, string

acsStsAddress)

{

WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(

new

WindowsWSTrustBinding(SecurityMode.TransportWithMessageCredential),

new EndpointAddress(new Uri(stsAddress)));

trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;

RequestSecurityToken rst = new

RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue,

WSTrust13Constants.KeyTypes.Bearer);

rst.AppliesTo = new EndpointAddress(acsStsAddress);

Page 56: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

rst.TokenType =

Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11;

WSTrustChannel channel =

(WSTrustChannel)trustChannelFactory.CreateChannel();

GenericXmlSecurityToken token = channel.Issue(rst) as

GenericXmlSecurityToken;

return token.TokenXml.OuterXml;

}

The code here takes advantage of the object model for Windows Identity Foundation, and

specifically of the WSTrustChannel class which makes it easy to send issuing requests to a WS-

Trust STS.

7. The code in step 5 makes use of the GetACSToken method, which gets a token from AppFabric

AC based on the SAML token. Add the definition of GetACSToken by coping the following code

at the end of Program class.

(Code Snippet – Introduction to AppFabric AC Lab - Ex02 GetACSToken Method)

C#

public class Program

{

...

private static string GetSamlAssertion(string stsAddress, string

acsStsAddress)

...

private static string GetACSToken(string samlAssertion)

{

WebClient tokenClient = new WebClient();

tokenClient.BaseAddress = string.Format("https://{0}.{1}",

ServiceNamespace, AcsHostName);

NameValueCollection values = new NameValueCollection();

values.Add("wrap_assertion_format", "SAML");

values.Add("wrap_assertion", samlAssertion);

values.Add("wrap_scope", "http://localhost/weatherforecast");

byte[] responseBytes = tokenClient.UploadValues("WRAPv0.9", values);

string response = Encoding.UTF8.GetString(responseBytes);

return response

.Split('&')

Page 57: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

.Single(value => value.StartsWith("wrap_access_token=",

StringComparison.OrdinalIgnoreCase))

.Split('=')[1];

}

}

You can see how the method body here closely resembles the code we used in exercise 1 for

performing a similar function with a symmetric key.

8. Add the code that will add the AppFabric AC token in the authorization HTTP header. To do

that, add the following code right before calling the service.

(Code Snippet – Introduction to AppFabric AC Lab - Ex02 WRAP Header)

C#

using (new OperationContextScope(proxy as IContextChannel))

{

string authHeaderValue = string.Format("WRAP access_token=\"{0}\"",

HttpUtility.UrlDecode(acsToken));

WebOperationContext.Current.OutgoingRequest.Headers.Add("authorization",

authHeaderValue);

// call the service and get a response

try

{

...

Exercise 2: Verification

In order to verify that you have correctly performed all steps in exercise two, proceed as follows:

1. Right click on the Service project (in Solution Explorer), and select Debug | Start new instance

to run the Service.

Page 58: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Figure 42

Service console

2. Right click on the Client project (in Solution Explorer), and select Debug | Start new instance to

run the Client.

Figure 43

Client console showing the 3 days forecast but not the 10 days forecast because the user doesn’t

have access to that.

3. Verify that the 3 days forecast is retrieved by looking at the console output. You'll also notice

that the console displays an error on the following line. This is exactly in line with expectations:

Page 59: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

our rule granted this client access only to the Get3DaysForecast method , hence the attempt to

access Get10DaysForecast was blocked with a (401) Unauthorized return code. This happened

because the STS generated a SAML token with a group claim with value “Pilots” and we created

an AppFabric AC rule that transform the group claim “Pilots” to Get3DaysForecast.

Note: As an optional exercise, you can try to create a second rule that would grant access to

the Get10DaysForecast action for the “Pilots” group. Hint: you can follow the same procedure

we illustrated in the verification section of exercise 1.

Exercise 2: Summary

In this exercise you have learned how to take advantage of ADFSv2 identities for managing access

control to REST services. What made the scenario possible is the ability of the AppFabric AC of

processing SAML tokens issued by ADFSv2, transforming the claims from the incoming SAML assertion in

authorization directives in the resulting SWT token.

Exercise 2 used the same service you developed in exercise 1: however the entire exercise 2 was

completed without touching the code of the service. The service was already configured to trust SWT

tokens issued by AppFabric AC, hence all it was needed for enabling a new service consumer was few

calls to the AppFabric AC management service.

Summary

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

Modify your WCF services to take advantage of AppFabric AC for handling access control

Create and manage AppFabric AC Service Namespaces; work with token policies, issuers, scopes

and rules

Invoke REST web services secured by AppFabric AC

Obtain tokens from AppFabric AC via SAML token, and use them to invoke REST web services

You can easily generalize what you have learned here to different scenarios or technologies: since all

you need is an HTTP-capable client, it is easy to imagine how to apply the steps you have seen in this lab

for requesting tokens from the widest range of platforms, devices and programming styles. As you have

seen in the two exercises, once your REST services are configured to trust AppFabric AC it does not really

Page 60: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

matter which technology or credentials your clients will use: your services are decoupled from those

changes.

When advanced capabilities are available, AppFabric AC is ready to take advantage of them: you can use

what you learned in exercise 2 for taking advantage of your investment in Active Directory and ADFSv2

for extending to the REST world the sophisticated claims-based access control policies that until now

were available only to WS-* stacks.

We hope that the lab inspired you to think about how the AppFabric AC can help you solve your access

control challenges, and we invite you to experiment with the SDK and all the rest of the learning

material Microsoft offers on this topic.

Appendix 1 - Using the AppFabric Access

Control Management Command Line

Tool

If you are used to command line interfaces for administration, there is a command line tool available to

control AppFabric AC, which allows you to create, update and delete Scopes, Policies, Issuers, and Rules.

The command line tool (ACM.exe) is part of the SDK and is copied in the Assets folder of the labs for

your convenience. You need to configure ACM.exe to refer to your Service Namespace and use your

management key. Locate Acm.exe.config in the Source\Assets folder of this Lab and open it in Visual

Studio.

Change the value of the “service” entry to the name of your Service Namespace. Change the value of the

entry “mgmtKey” to the value of the management key for your Service.

XML

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="service" value="{insert service name here}"/>

<add key="mgmtKey" value="{insert management key here}" />

<add key="host" value="accesscontrol.windows.net"/>

</appSettings>

</configuration>

These are some of the commands executed throughout the lab. These also can be found in Setup.ps.txt

of each exercise folder.

[CREATE_TOKENPOLICY]

Page 61: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0

Powershell

# create a tokenpolicy (store the generated id in a variable)

$tokenpolicyid = .\acm.exe create tokenpolicy -name:weatherforecast -autogeneratekey

-simpleout

[CREATE_SCOPE]

Powershell

$scopeid = .\acm.exe create scope -name:weatherforecast -

appliesto:http://localhost/weatherforecast -tokenpolicyid:$tokenpolicyid -simpleout

[CREATE_ISSUER]

Powershell

$issuerid = .\acm.exe create issuer -name:weatherforecastclient -

issuername:weatherforecastclient -autogeneratekey -simpleout

[CREATE_RULE]

Powershell

.\acm.exe create rule -scopeid:$scopeid -inclaimissuerid:$issuerid -

inclaimtype:Issuer -inclaimvalue:weatherforecastclient -outclaimtype:action -

outclaimvalue:Get3DaysForecast -name:client3days

[GET_TOKENPOLICY_KEY]

Powershell

.\acm.exe get tokenpolicy -id:$tokenpolicyid

[GET_ISSUER_KEY]

Powershell

.\acm.exe get issuer -id:$issuerid

[CREATE_RULE_10DAYS]

Powershell

.\acm.exe create rule -scopeid:$scopeid -inclaimissuerid:$issuerid -

inclaimtype:Issuer -inclaimvalue:weatherforecastclient -outclaimtype:action -

outclaimvalue:Get10DaysForecast -name:client10days

Page 62: Introduction to the AppFabric Access Controlaz12722.vo.msecnd.net/wazplatformtrainingcourse2-02/Labs/IntroApp... · Introduction to the AppFabric Access Control Lab version: 2.0.0