Sample Chapters from Programming Windows Identity...

75

Transcript of Sample Chapters from Programming Windows Identity...

Page 1: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing
Page 2: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Sample ChaptersCopyright © 2011 by Vittorio Bertocci

All rights reserved.

To learn more about this book visit http://go.microsoft.com/fwlink/?Linkid=196688.

Page 3: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

vii

Table of ContentsForeword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xi

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xiii

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Part I WindowsIdentityFoundationforEverybody 1 Claims-Based Identity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

What Is Claims-Based Identity? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Traditional Approaches to Authentication . . . . . . . . . . . . . . . . . . . . . . . . 4Decoupling Applications from the Mechanics of Identity and Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

WIF Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15An API for Claims-Based Identity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16WIF’s Essential Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16IClaimsIdentity and IClaimsPrincipal . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2 Core ASP .NET Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Externalizing Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

WIF Basic Anatomy: What You Get Out of the Box . . . . . . . . . . . . . . . . 24Our First Example: Outsourcing Web Site Authentication to an STS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Authorization and Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33ASP .NET Roles and Authorization Compatibility . . . . . . . . . . . . . . . . . . 36Claims and Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37A First Look at <microsoft .identityModel> . . . . . . . . . . . . . . . . . . . . . . . 39Basic Claims-Based Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Microsoft is interested in hearing your feedback so we can continually improve our books and learning resources for you. To participate in a brief online survey, please visit:

www.microsoft.com/learning/booksurvey/

What do you think of this book? We want to hear from you!

Page 4: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

viii Table of Contents

Part II WindowsIdentityFoundationforIdentityDevelopers

3 WIF Processing Pipeline in ASP .NET . . . . . . . . . . . . . . . . . . . . . . . . 51Using Windows Identity Foundation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52WS-Federation: Protocol, Tokens, Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . 54

WS-Federation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55The Web Browser Sign-in Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57A Closer Look to Security Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Metadata Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

How WIF Implements WS-Federation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72The WIF Sign-in Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

WIF Configuration and Main Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82A Second Look at <microsoft .identityModel> . . . . . . . . . . . . . . . . . . . . . 82Notable Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

4 Advanced ASP .NET Programming . . . . . . . . . . . . . . . . . . . . . . . . . 95More About Externalizing Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

Identity Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Federation Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99The WIF STS Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Single Sign-on, Single Sign-out, and Sessions . . . . . . . . . . . . . . . . . . . . . . . . 112Single Sign-on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Single Sign-out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115More About Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

Federation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Transforming Claims . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Pass-Through Claims . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134Modifying Claims and Injecting New Claims . . . . . . . . . . . . . . . . . . . . 135Home Realm Discovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Step-up Authentication, Multiple Credential Types, and Similar Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

Page 5: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Table of Contents ix

Claims Processing at the RP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142Authentication and Claims Processing . . . . . . . . . . . . . . . . . . . . . . . . . 142

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

5 WIF and WCF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Passive vs . Active . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146Canonical Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154Custom TokenHandlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163Object Model and Activation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

Client-Side Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170Delegation and Trusted Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . 170Taking Control of Token Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

6 WIF and Windows Azure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

Packages and Config Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187The WIF Runtime Assembly and Windows Azure . . . . . . . . . . . . . . . . 188Windows Azure and X .509 Certificates . . . . . . . . . . . . . . . . . . . . . . . . . 188

Web Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191Endpoint Identity and Trust Management . . . . . . . . . . . . . . . . . . . . . . 192

WCF Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Service Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196Tracing and Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

WIF and ACS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204Custom STS in the Cloud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Dynamic Metadata Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205RP Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Page 6: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

x Table of Contents

7 The Road Ahead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215New Scenarios and Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

ASP .NET MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216Silverlight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223SAML Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229Web Identities and REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Microsoft is interested in hearing your feedback so we can continually improve our books and learning resources for you. To participate in a brief online survey, please visit:

www.microsoft.com/learning/booksurvey/

What do you think of this book? We want to hear from you!

Page 7: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

3

Chapter1

Claims-Based IdentityIn this chapter:What Is Claims-Based Identity? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3WIF Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

MicrosoftWindowsIdentityFoundation(WIF)enablesyoutoapplytheprinciplesofclaims-basedidentitywhensecuringyourMicrosoft.NETapplication.Claims-basedidentityissoimportantthatIwanttomakesureyouunderstanditwellbeforeIformallyintroduceWindowsIdentityFoundation.

Claims-basedidentityisanaturalwayofdealingwithidentityandaccesscontrol.However,theoldwaysofdoingthisarewellestablished,sobeforedelvingintothenewapproach,it’susefultodescribeandchallengetheclassicassumptionsaboutauthenticationandauthoriza-tion.Onceyouhaveaclearunderstandingofsomeoftheissueswithtraditionalapproaches,I’llintroducethebasicprinciplesofclaims-basedidentity—I’llsayenoughtoenableyoutoproficientlyuseWindowsIdentityFoundationforthemostcommonscenarios.Thischaptercontainssomesimplificationsthatwillgetyougoingwithoutoverloadingyouwithinfor-mation.Foramorethoroughcoverageofthesubject,refertoPartII,“WindowsIdentityFoundationforIdentityDevelopers.”

Finally,we’lltakeourinitiallookathowWIFimplementsthemechanismsofclaims-basedidentityandhowyou,thedeveloper,canaccessthemainelementsexposedbyitsobjectmodel.

Afterreadingthischapter,you’llbeabletodescribehowclaims-basedidentityworksandhowtotakeadvantageofitinsolutionstocommonproblems.Furthermore,you’llbeabletodefineWindowsIdentityFoundationandrecognizeitsmainelements.

WhatIsClaims-BasedIdentity?

Note Ifyoualreadyknowaboutclaims,feelfreetoskipaheadtothe“WIFProgrammingModel”section.Ifyouareinabighurry,Iofferyouthefollowingsummaryofthissectionbeforeyouskiptothenextsection:Claims-basedidentityallowsyoutooutsourceidentityandaccessmanagementtoexternalentities.

Page 8: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

4 Part I Windows Identity Foundation for Everybody

Theproblemofrecognizingpeopleandgrantingaccessrightstothemisoneoftheoldestinthehistoryofcomputerscience,andithasitsrootsinidentityandaccessproblemsweallexperienceeverydayaswegothroughourlives.

Althoughwecanclassifyalmostallthesolutionstotheprobleminrelativelyfewcategories,anincrediblenumberofsolutionstailoredspecificallytosolvethisorthatproblemexists.Fromtheinnumerablewaysofhandlingusernamesandpasswordstothemostexotichardware-basedcryptographysolutions,thepanoramaofidentityandaccessmeth-odscreatesasequenceofsystemsthatarealmostnevercompatible,eachwithdifferentadvantages,disadvantages,tradeoffs,andsoon.

Fromthedeveloperperspective,thisstatusquoisbadnews:thisdiversityforcesyoutocontinuallyrelearnhowtodothesamethingwithdifferentAPIs,exposesyoutodetailsofthesecuritymechanismsthatyou’drathernotberesponsiblefor,andsubjectsyoutosoftwarethatisbrittleanddifficulttomaintain.

Whatyouneedisawaytosecureyourapplicationswithouthavingtoworkdirectlyatthesecuritymechanismlevel:anabstractionlayer,whichwouldallowyoutoexpressyoursecu-rityrequirements(the“what”)withoutgettingcaughtinthespecificsofhowtomakethathappen(the“how”).IfyourspecialtyisdesigninguserexperiencesforMicrosoftASP.NET,youshouldbeallowedtofocusyoureffortonthataspectofthesolutionandnotbeforcedtobecomeanexpertinsecurity(beyondthebasic,secure-codingbestpractices,ofcourse—alldevelopersneedtoknowthose).

If you need a good reference on secure coding best practices, I highly recommend WritingSecureCode,SecondEdition, by Michael Howard and David LeBlanc (Microsoft Press, 2002).

Whatwecollectivelycall“claims-basedidentity”providesthatlayerofabstractionandhelpsyouavoidtheshortcomingsoftraditionalsolutions.Claims-basedidentitymakesitpossibletohavetechnologiessuchasWindowsIdentityFoundation,whichenablesyoutosecuresystemswithoutbeingrequiredtounderstandthefinedetailsofthesecuritymechanismsinvolved.

Traditional Approaches to AuthenticationBeforewegoanyfurther,letmebeabsolutelyclearonakeypoint:thisbookdoesnotsuggestthattraditionalapproachestoauthenticationandauthorizationarenotsecureorsomehowbadper se.Infact,theyusuallydoverywellinsolvingtheproblemtheyhavebeendesignedtotackle.Theissuesarisewhenyouhavetodealwithchangesoryouneeddiffer-entsystemstoworktogether.Becauseasinglesystemcan’tsolveallproblems,youareoftenforcedtore-performthesametaskwithdifferentAPIstoaccommodateevensmallchangesinyourrequirements.

Page 9: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 5

It’sbeyondthescopeofthisbooktogiveanexhaustivelistofauthenticationsystemsandtheircharacteristics;fortunately,thatwon’tbenecessaryformakingourpoint.InthissectionI’llbrieflyexaminethebuilt-inmechanismsofferedbythe.NETFrameworkandprovidesomeexamplesofhowtheymightnotalwaysofferacompletesolution.

IPrincipal and IIdentityManagingidentityandaccessrequiresyoutoacquireinformationaboutthecurrentusersothatyoucanmakeinformeddecisionsabouttheuser’sidentityclaimsandwhatactionsbytheusershouldbeallowedordenied.

Ina.NETapplicationtheuserinthecurrentcontextisrepresentedbyanIIdentity,asimpleinterfacethatprovidesbasicinformationabouttheuserandhowtheuserwasauthenticated:

public interface IIdentity { // Properties string AuthenticationType { get; } bool IsAuthenticated { get; } string Name { get; } }

IIdentitylivesinsideIPrincipal,anotherinterfacethatcontainsmoreinformationabouttheuser(suchaswhetherhebelongstoacertainsecuritygroup)thatcanbeusedinauthorizationdecisions:

public interface IPrinicipal { // Methods bool IsInRole(string role); // Properties IIdentity Identity { get; } }

YoucanalwaysreachthecurrentIPrincipalinthecodeofyour.NETapplication:inASP.NET,youwillfinditinHttpContext.Current.User,andingeneral,you’llfinditinThread.CurrentPrincipal.

IPrincipalandIIdentity,astheyexistoutofthebox,doprovidesomegooddecouplingfromhowtheauthenticationactuallyhappened.Theydonotforceyoutodealwiththedetailsofhowthesystemcametoknowhowtheinformationabouttheuserwasacquired.Ifyourusersareallowedtoperformacertainactiononlyiftheyareadministrators,youcanwriteThread.CurrentPrincipal.IsInRole(“Administrators”)withouthavingtochangeyourcodeaccordingtotheauthenticationmethod.TheframeworkusesdifferentextensionsofIPrincipal—WindowsPrincipal,GenericPrincipal,oryourowncustomclass—toaccom-modatethespecificmechanism,andyoucanalwayscastfromIPrincipaltooneofthose

Page 10: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

6 Part I Windows Identity Foundation for Everybody

classesifyouneedtoaccesstheextrafunctionalitiestheyprovide.However,ingeneral,usingIPrincipaldirectlymakesyourcodemoreresilienttochanges.

Unfortunately,theprecedingdiscussionisjustatinypartofwhatyouneedtoknowabout.NETsecurityifyouwanttoimplementarealsystem.

Populating IPrincipalMostoftheinformationyouneedtoknowabouttheuserisinIPrincipal,buthowdoyougetthatinformationinthere?ThevaluesinIPrincipalaretheresultofasuccessfulauthentication:beforebeingabletotakeadvantageoftheapproach,youhavetoworryaboutmakingtheauthenticationstephappen.Thatiswherethingsmightstartgettingconfusingifyoudon’twanttoinvestalotinsecurityknow-how.

WhenIjoinedMicrosoftin2001,mybackgroundwasmainlyinscientificvisualizationandwithSiliconGraphics;IknewnothingaboutMicrosofttechnologies.OneofthefirstprojectsIworkedonwasaline-of-businessapplicationforacustomer’sintranet.TodayIcansayI’vehadmyfairshareofexperiencewith.NETandauthentication,butIcanstillrecalltheconfu-sionIexperiencedbackthen.Let’stakealookatsomeconcreteexamplesofusingIPrincipal.

UpuntilthereleaseofMicrosoftVisualStudio2008,ifyoucreatedaWebsitefromthetemplate,thedefaultauthenticationmodewasWindows.ThatmeansthattheapplicationexpectsInternetInformationServices(IIS)totakecareofauthenticatingtheuser.However,ifyouinspecttheIPrincipalinsuchanapplicationyouwillfinditlargelyempty.ThisisbecausetheWebapplicationhasanonymousauthenticationenabledinIISbydefault,sonoattempttoauthenticatetheuserismade.Thisisthefirstbreachintheabstraction:youhavetoleaveyourdevelopmentenvironment,gototheIISconsole,disableanonymousauthentication,andexplicitlyenableWindowsauthentication.(Youcoulddothisdirectlybymodifyingtheweb.configfileoftheapplicationinMicrosoftVisualStudio,butgoingthroughIISisstillthemostcommonapproachinmyexperience.)

AfteryouadjusttheIISauthenticationtypes,you’regoodtogo,atleastaslongasyouremainwithintheboundariesoftheintranet.Ifyouaredevelopingonyourdomain-joinedlaptopandyoudecidetoburnsomemidnightoilathomeworkingonyourapplication,don’tbesurprisedifyourcallstoIsInRolenowfail.Withoutthenetworkinfrastructurereadilyavailable,thenamesofthegroupstowhichtheuserbelongscannotberesolved.Asyoucanimagine,thesamethinghappensiftheapplicationismovedtoahoster,tothecloud,oringeneralawayfromyourcompany’snetworkenvironment.

Infact,you’llencounterpreciousfewcasesinwhichyouenjoytheluxuryofhavingauthenticationtakencareofbytheinfrastructure.Iftheusersyouwanttoauthenticateliveoutsideofyourdirectory,youarenormallyforcedtotakethematterintoyourownhandsanduseauthenticationAPIs.ThatusuallymeansconfiguringyourASP.NETapplicationtouse

Page 11: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 7

Formsauthentication,perhapscreatingandpopulatingausersandrolesstoreaccordingtotheschemaimposedbysqlMembershipProvider,implementingyourownMembershipProviderifyourscenariocannotfitwhatisavailableoutofthebox,andsoon.

There’smore:noteverythingcanbesolvedbyprovidingacustomuserstore.Often,yourusersarealreadyprovisionedinanexistingstorebutthatstoreisnotunderyourdirectcontrol.(Thinkaboutemployeesofbusinesspartners,suppliers,andcustomers.)Storedupli-cationissometimesanoption,butitnormallybringsmoreproblemsthantheonesitsolves.ASP.NETprovidesmechanismsforextendingFormsauthenticationtothosecases,buttheyrequireyoutolearnevenmoresecurityand,aboveall,theyarenotguaranteedtoworkwithotherplatforms.

Ifyou’vedealtwithsecurityissuesinthepast,youcancertainlyrelatetowhatI’vejustdescribed.Ifyouhaven’t,don’tworryifyoudidn’tunderstandeverythinginthelastcoupleofparagraphs.Youcanstillunderstandthatyouneedtolearnalottoaddauthenticationcapabilitiestoyourapplication,despiteASP.NETprovidingyouwithhelperclasses,tooling,andmodels.Ifyou’renotinterestedinbecomingasecurityexpert,youwouldprobablyratherspendyourtimeandenergyonsomethingelse.

Here’sonelastnotebeforemovingon.WhenusingFormsauthentication,youdoneedtowriteextracodefortakingcareofauthentication,butintheendyoucanstillusetheIPrincipalabstraction.(Theuser’sinformationiscopiedfromaFormsIdentityobjectintoaGenericPrincipal.)Thismightinduceyoutothinkthatallyouneedisbettertoolingtohandleauthenticationandthattheabstractionisalreadytherightone.You’reontherighttrack,butthisisnotthecaseifyoustickwiththecurrentideaofauthentication.Imagineacaseinwhichyouwantauthenticationtohappenusingradicallydifferentcredentials,suchasaclientSecureSocketsLayer(SSL)certificate,butthosecredentialsdonotmaptoexistingWindowsusers.Inthetraditionalcase,youhavetodirectlyinspecttherequestfortheincomingX.509certificateandlearnnewconcepts(subject,thumbprint,andsoon)toperformthesametaskyoualreadyknowhowtodowithotherAPIs.

TheproblemhereisnotwithhowASP.NEThandlesauthentication:itissystemic,andyou’dhavethesameissueswithanyothergeneral-purposetechnology.Bytheway,ifyouconsiderhowtohandleidentityandaccesswithMicrosoftWindowsCommunicationFoundation(WCF),youhavetolearnyetanothermodel,onethatislargelyincompatiblewithwhatwehaveseensofarandwithitsownrangeofAPIsandexceptions.

Whenyoucanrelyoninfrastructure,likeintheWindowsAuthenticationexample,youdofine:mostdetailsarehandledbyWindows,andallthat’sleftforyouisdecidingwhattodowiththeuserinformation.Whenyoucan’trelyontheinfrastructure,asinthegenericcase,youcanobserveaconsistentissueacrossallcases:youareburdenedwiththeresponsibil-ityofdrivingthemechanicsofauthentication,andthatoftenmeansdealingwithcomplexissues.AsI’vealreadystressed,thegamutofallauthenticationoptionsiswide,diverse,and

Page 12: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

8 Part I Windows Identity Foundation for Everybody

constantlyevolving.Toolingcanhelpyouonlysofar,anditisdoomedtobeobsoleteassoonasanewauthenticationschemeemerges.

Whatshoulddevelopersdo?ArewedoomedtooperateinaninfinitearmsracebetweenauthenticationsystemsandtheAPIssupportingthem?

Decoupling Applications from the Mechanics of Identity and AccessOnceuponatime,developerswereforcedtohandlehardwarecomponentsdirectlyintheirapplications.Ifyouwantedtoprintaline,youneededtoknowhowtomakethathappenwiththespecifichardwareoftheprintermodelinuseintheenvironmentofyourcustomer.

Thosedaysarefortunatelylonggone.Today’ssoftwaretakesadvantageoftheavailablehardwareviadevice drivers.Adevicedriverisaprogramthatactsasanintermediarybe-tweenagivendeviceandthesoftwarethatwantstouseit.Alldrivershaveonelogical layer,whichexposesagenericrepresentationofthedeviceandthefunctionalitiesthatarecommontothedeviceclassandrevealsnodetailsaboutthespecifichardwareofagivendevice.Thelogicallayeristhelayerwithwhichthehigherlevelsoftwareinteracts—forexample,“printthisstring.”Thedrivercontainsaphysical layertoo,whichistailoredtothespecifichardwareofagivendevice.Thephysicallayertakescareoftranslatingthehigh-levelcommandsfromthelogicallayertothehardware-specificinstructionsrequiredbytheexactdevicemodelbeingused—forexample,“putthisbytearrayinthatregister,”“addthefollowingdelimiter,”“pushthefollowinginstructionsinthestack,”andsoforth.

Ifyouwanttoprintfromyour.NETapplication,youjustcallsomemethodonPrintDocument,whichwilleventuallytakeadvantageofthelocaldriversandmakethathappenforyou.Whocaresaboutwhichprintermodelwillactuallybeavailableatruntime?

Doesn’tthisscenariosoundawfullyfamiliar?Managinghardwaredirectlyfromapplicationsissimilartotheproblemofdealingwithauthenticationandauthorizationfromapplications’code:therearetoomany(difficult!)detailstohandle,andresultsaretooinflexibleandvul-nerabletochanges.Thehardwareproblemwassolvedbytheintroductionofdevicedrivers;thereisreasontobelievethatasimilarapproachcansolvetheaccessmanagementproblem,too.

Althoughanoperatingsystemprovidesanenvironmentconducivetothecreationofathrivingdriverecosystem,theidentityandaccessproblemspacepresentsitsownchallenges—forexample,authenticationtechnologiesandprotocolsbelongtomanydif-ferentowners,thewaysinwhichresourcesandservicesareaccessedisconstantlychangingandisfragmentedinmanydifferentsegments,differentusesimplydramaticallydifferentusabilityandsecurityrequirements,usersanddataareoftensealedininaccessiblesilos,and

Page 13: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 9

soon.Thechancesofalevelofindirectionspontaneouslyemergingfromthatchaosarepracticallyzero.

Withtheinflationarygrowthofdistributedsystemsandonlinebusinesses,inthelastfewyearstheincreasingneedforinteroperableprotocolsthatcouldteardownthewallsbetweensilosbecameclear.ThebigplayersintheITindustrygottogetherandagreedonasetofcommonprotocolsthatwouldsupportinteroperablecommunicationsacrossdifferentplatforms.SomeexamplesofthoseprotocolsareSOAP,WS-Security,WS-Trust,WS-Federation,SecurityAssertionMarkupLanguage(SAML),andinmorerecenttimes,OpenID,OAuth,andotheropenprotocols.Don’tworryifyoudon’trecognizesomeoranyofthosenames.Whatisimportanthereisthattheemergenceofcommonprotocols,combinedwiththeextraattentionthatthesecurityaspectscommandedintheirredaction,finallycreatedtheconditionsforintroducingthemissinglogicallayerinidentityandaccessmanagement.Itisthatextralayerthatwillmakeitpossibletoisolateapplicationsandtheirdevelopersfromthegorydetailsofauthenticationandauthorizationmechanics.Inthispart,Iamnotgoingtogointothedetailsofwhatthoseprotocolsareorhowtheywork;instead,Iwillconcentrateonthescenariosthattheyenableandhowtotakeadvantageofthem.

Nowthatyou’vegainedsomeperspectiveonwhytoday’sapproachesarelessthanideal,itistimetofocusonhowyoucanmovebeyondthem.

Authentication and Authorization in Real LifeImaginingwhatshouldbeinthelogicallayerofaprinterdriveriseasy.Afterall,youhaveagoodideaofwhataprinterissupposedtodoandhowyou’dliketotakeadvantageofitinyourcode.Nowthatyouknowitispossibletocreatealogicallayerforidentity,doyouknowwhatitshouldlooklike?WhichkindofAPIshouldyouoffertodevelopers?

Wehavebeenhandlinglow-leveldetailsforsolongthatitmaybehardtoseethebiggerpicture.Ausefulexerciseistostepbackandspendamomentanalyzinghowidentityisactuallyusedforauthorizationintherealworld,andseeifwhatyoulearncanbeofhelpindesigningyournewidentitylayer.Let’slookataneasyexample.

Imagineyouaregoingtoamovietheatertoseeadocumentaryfilm.Considerthefollowingfacts:

1. Thedocumentarycontainsscenesthatarenotsuitableforayoungandimpression-ableaudience;therefore,theclerkattheboxofficeasksyouforapictureIDsothathecanverifywhetheryouareoldenoughtowatchthefilm.Youreachforyourwalletandextractyourdriver’slicense,andinsodoingyourealizethatitisexpired.

2. Resignedtomissingthefirstshow,youwalktoanearbyofficeoftheDepartmentofLicensing(DOL).AttheDOL,youhandoveryourolddriver’slicenseandasktogetanewone.

Page 14: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

10 Part I Windows Identity Foundation for Everybody

3. Theclerktakesagoodlookatyoutoseewhetheryoulooklikethephotoonrecord.Perhapsheasksyoutoreadafewlettersfromaneyetestchart.Whenhe’ssatisfiedthatyouarewhoyouclaimtobe,hehandsyouyournewdriver’slicense.

4. Yougobacktothemovietheaterandpresentyournewdriver’slicensetotheclerk.Theclerk,nowsatisfiedthatyouareoldenoughtowatchthemovie,issuesyouaticketforthenextshow.

Figure1-1showsadiagramofthetransactionjustdescribed.

FIGURE1-1Oneidentitytransactiontakingplaceinreallife

Thisiscertainlynotrocketscience.Wegothroughsimilarinteractionsallthetime,fromwhenweboardaplanetowhenwedealwithourinsurancecompanies.Yet,thestorycontainspreciouscluesabouthowwecanaddourmissingidentitylayer.

Let’sconsiderthingsfromtheperspectiveofthebox-officeclerk.Theclerkregulatesaccesstothemovie,actuallyauthorizing(orblocking)viewersfromacquiringaticket.Thequestionthattheclerkneedstoansweris,“IsthispersonolderthanX?”Herecomestheinterestingpart:thebox-officeclerkdoesnotverifyyouragedirectly.Howcouldhe?Instead,hereliesontheverificationthatsomebodyelsealreadydid.Inthiscase,theDOLcertifiedyourbirthdateinitsdriver’slicensedocument.Thebox-officeclerktruststheDOLtotellthetruthaboutyourage.TheDOLisarecognizedgovernmentinstitution,andithasasolidbusinessneedtoknowaperson’scorrectagebecauseitisrelevanttothatperson’sabilitytodrive.Theoutcomeoftheinteractionwouldbedifferentifyoupresentedthebox-officeclerkastickynoteonwhichyouscribbledyourage.Insuchatransaction,youarenotatrustworthysource.(Unlesstheclerkknowsyoupersonally,hemustassumebiasonyourpart—thatis,youcouldlieinordertogetintothemovietheater.)

Page 15: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 11

Notethatinthisscenarioyoupresentedadriver’slicenseasproofofage,butfromtheclerk’spointofviewnotmuchwouldhavechangedifyouhadusedyourpassportoranyotherdocumentas long as the institution issuing it is known and trusted by the box office clerk.

Onelastthoughtbeforedrawingourparalleltosoftware:thebox-officeclerkdoesnotknowwhichproceduretheDOLclerkfollowedforissuingyouadriver’slicense,howtheDOLverifiedyouridentity,whichthingsheverified,andhowheverifiedthem.HedoesnotneedtoknowthesethingsbecauseoncehedecideshetruststheDOLtocertifyagecorrectly,he’llbelieveinwhateverbirthdateappearsonavaliddriver’slicensewiththepictureofthebearer.

Let’ssummarizeourobservationsinthisscenario:

■ Thebox-officeclerkdoesnotverifythecustomer’sagedirectly,butreliesonatrustedparty(theDOL)todosoandfindstheresultinadocument(thedriver’slicense).

■ Thebox-officeclerkisnottiedtoaparticulardocumentformatorsource.Aslongastheissueristrustedandtheformatisrecognized,theclerkwillacceptthedocument.

■ Thebox-officeclerkdoesnotknoworcareaboutthedetailsofhowthecustomerhasbeenidentifiedbythedocumentissuer.

Thissoundsquiteefficient.Infact,similartransactionshavebeensuccessfullytakingplaceforthelastfewthousandyearsofcivilization.It’shightimethatwelearnhowtotakeadvantageofsuchtransactionsinoursoftwaresolutionsaswell.

Claims-Based Identity: A Logical Layer for IdentityThetransactiondescribedintheprecedingsection,includingthevariousrolesthattheactorsplayedinit,canbegeneralizedinoneofthemostuniversalpatternsinidentityandaccessandformsthebasisofclaims-basedidentity.Thepatterndoesnotimposeanyspecifictech-nology,althoughitdoesassumethepresenceofcertaincapabilities,anditcontainsalltheindicationsyouneedfordefiningyourlogicalidentitylayer.

Let’strytoextractfromthestoryagenericpatterndescribingagenericauthenticationandauthorizationsystem.Paycloseattentionforthenextfewparagraphs.Onceyouunderstandthispattern,itisyoursforever.Itwillprovideyouwiththekeyfordealingwithmostofthescenariosyouencounterinimplementingidentity-basedtransactions.

Entities Figure1-2showsthemainentitiesthatplayaroleinmostidentity-basedtransactions.

Page 16: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

12 Part I Windows Identity Foundation for Everybody

Relying PartySubject

SecurityToken

Claim

Identity Provider

FIGURE1-2 Themainentitiesinclaims-basedidentity

Let’ssaythatoursystemincludesauser,whichinliteratureisoftenreferredtoasasubject,andtheapplicationtheuserwantstoaccess.Inourearlierexample,thesubjectwasthemoviegoer;inthegeneralcase,asubjectcanbeprettymuchanythingthatneedstobeidentified,fromanactualusertotheapplicationidentitiesofunattendedprocesses.

TheapplicationcanbeaWebsite,aWebservice,oringeneralanysoftwarethathasaneedtoauthenticateandauthorizeusers.Inidentityjargon,itiscalledarelying party,oftenabbreviatedasRP.Inourearlierexample,theRPisthecombinationofthebox-officeclerkandmovietheater.

Thesystemmightincludeoneormoreidentity providers(IPs).AnIPisanentitythatknowsaboutsubjects.Itknowshowtoauthenticatethem,liketheDOLintheexampleknewhowtocomparethecustomer’sfacetoitspicturearchives;itknowsfactsaboutthecustomer,liketheDOLknowsaboutthebirthdateofeverylicenseddriverinitsregion.Anidentitypro-viderisanabstractrole,butitrequiresconcretecomponents:directories,userrepositories,andauthenticationsystemsareallexamplesofpartsoftenusedbyanidentityprovidertoperformitsfunction.

WeassumethatasubjecthasstandardwaysofauthenticatingwithanIPandreceivinginreturnthenecessaryuserinformation(likethebirthdateintheexample)foraspecificidentitytransaction.Wecallthatuserinformationclaims.

Themagicalword“claim”finallycomesout.A claim is a statement about a subject made by an entity.Thestatementcanbeliterallyanythingthatcanbeassociatedwithasubject,fromattributessuchasbirthdatetothefactthatthesubjectbelongstoacertainsecuritygroup.Aclaimisdistinctfromasimpleattributebythefactthataclaimisalwaysassociatedwiththeentitythatissuedit.Thisisanimportantdistinction:itprovidesyouwithacriterionfordecid-ingifyouwanttobelievethattheassertionappliestothesubject.Recalltheexampleofthebirthdateprintedonthedriver’slicenseversusabirthdatescribbledonastickynote:theclerkbelievestheformerbutnotthelatterbecauseoftheentitiesbackingtheassertion.

Page 17: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 13

Claimstravelacrossthenodesofdistributedsystemsinsecurity tokens,whichareXMLorbinaryfragmentsconstructedaccordingtosomesecuritystandard.Tokensaredigitallysigned,whichmeansthattheycannotbetamperedwithandthattheycanalwaysbetracedbacktotheIPthatissuedthem(whichprovidesanicemechanismforassociatingtokencontentwithitsissuer,asrequiredbythedefinitionofclaims).

Flow Claimsarethecurrencyofidentitysystems:theyarewhatdescribethesubjectinthecurrentcontext,whattheIPproduces,andwhattheRPconsumes.Here’showthetransactionunfolds.

Wellbeforeyourtransactionstarts,theRPpublishesadocument,oftencalledapolicy,inwhichitadvertisesitssecurityrequirements:thingssuchaswhichsecurityprotocolstheRPunderstandsandsimilarinformation.Thisisanalogoustotheboxofficehangingupasignthatsays,“Bereadytoshowyourdriver’slicenseoryourpassporttotheclerk.”ThemostimportantpartoftheRPpolicyisthelistoftheidentityprovidersittrusts.Thisisequivalenttoanothersignattheboxofficespecifying,“Drivers’licensesfromU.S.statesonly;passportsfromSchengenTreatycountriesonly.”

Again,beforethetransactionstarts,theIPpublishesananalogouspolicydocumentthatadvertisesitsownsecurityrequirements.ThisdocumentprovidesinstructionsonhowtoasktheIPtoissueasecuritytoken.Inliterature,youwilloftenfindthatIPsoffertheirtokenissuanceservicesviaaspecialflavorofWebservices,calledSTS(SecurityTokenService).You’llreadmore(MUCHmore)aboutSTSthroughoutthebook.

Figure1-3summarizesthestepsofthecanonicalidentitytransaction.

Identity Provider

Relying PartySubject

SecurityToken

2

3

14

STSPolicy

Policy

5

FIGURE1-3 Theflowofthecanonicaltransactioninclaims-basedidentity

Here’sadescriptionofthatflow:

Page 18: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

14 Part I Windows Identity Foundation for Everybody

1. ThesubjectwantstoaccesstheRPapplication.Itdoesthatviaanagentofsomesort(abrowser,arichclient,andsoon).ThesubjectbeginsbyreadingtheRPpolicy.Insodoing,itlearnswhichidentityproviderstheRPtrusts,whichkindofclaimsarerequired,andwhichsecurityprotocolsshouldbeused.

2. ThesubjectchoosesoneoftheIPsthattheRPtrustandinspectsitspolicytofindoutwhichsecurityprotocolisrequired.ThenitsendsarequesttotheIPtoissueatokenthatmatchestheRPrequirements.ThisprocessistheequivalentofgoingtotheDOLandaskingforadocumentcontainingabirthdate.Insodoing,thesubjectisrequiredtoprovidesomecredentialsinordertoberecognizedbytheIP.ThedetailsoftheprotocolusedaredescribedintheIPpolicy.

3. TheIPprocessestherequest;ifitfindstherequesttobesatisfactory,itretrievesthevaluesoftherequestedclaims,sendingthembacktothesubjectintheformofasecuritytoken.

4. ThesubjectreceivesthesecuritytokenfromtheIPandsendsittogetherwithhisfirstrequesttotheRPapplication.

5. TheRPapplicationexaminestheincomingtokenandverifiesthatitmatchesalltherequirements(comingfromonetrustedIP,intheexpectedformat,nothavingbeentamperedwith,containingtherightsetofclaims,andsoon).Ifeverythinglooksasexpected,theRPgrantsaccesstothesubject.

ThissequenceofstepscoulddescribeauserbuyingsomethingonlineandpresentingtotheWebmerchantacreditscorefromafinancialinstitution;itcoulddescribetheuserofaWindowsPresentationFoundation(WPF)applicationaccessingaWebserviceonthelocalintranetbypresentingagroupmembershipclaimissuedfromthedomaincontroller;itcoulddescribeprettymuchanyidentitytransactionifyouassignthesubject,RP,andIProlesintherightway.

The .abstraction .layer .we .were .searching .for Thepatternwe’vebeendiscussingdescribesagenericidentitytransaction.Withoutgoingintodetailabouttheactualprotocolsandtech-nologiesinvolved,wecansaythatitjustmakesassumptionsaboutwhatcapabilitiesthosetechnologiesshouldhave,suchasthecapabilityofexposingpolicies.

Themodelisprofoundlydifferentfromwhatwehaveobservedinclassicapproaches:whereasatraditionalapplicationtakescareofauthenticationmoreorlessdirectly,heretheRPoutsourcesitentirelytoathirdparty,theidentityprovider.Thedetailsofhowauthenti-cationhappensarenolongeraconcernoftheapplicationdeveloper;allyouneedtodoisconfigureyourapplicationtoredirectuserstotheintendedidentityprovidersandbeabletoprocessthesecuritytokenstheyissue.Althoughyoucanusemanydifferentprotocolsforobtainingandusingasecuritytoken,theabstractideaofclaimsandsecuritytokensis

Page 19: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 15

nonspecificenoughtoallowyoutocreateagenericprogrammingmodelforrepresentingusersandtheoutcomeofauthenticationoperationswithoutexceptions.

Thosechangesinperspectivefinallyeliminatethesystemicflawthatpreventedusfromeradicatingfromtheapplicationcodetheexplicithandlingofidentitywithoutrelyingondemandinginfrastructure.Allthat’slefttodoisforplatformanddevelopertoolsproviderstotakeadvantageoftheclaims-basedidentitymodelintheirproducts.

Note Themodelisextremelyexpressive.Infact,youcaneasilyuseitforrepresentingtraditionalscenariostoo.IftheIPandtheRParethesameentity,youarebacktothecaseinwhichtheapplicationitselftakescareofhandlingauthentication.Theimportantdifferenceintheimplementationisthatbothcodeandarchitecturewillshowthatthisisjustaspecialcaseofamoregenericscenario.Therefore,thedecouplingwillberespectedandchangeswillbeaccommodatedgracefully.

WIFProgrammingModelMicrosofthasbeenamongthemostenthusiasticpromotersoftheclaims-basedidentitymodel.Itshouldcomeasnosurprisethatithasalsobeenoneofthefirsttointegrateitinitsproductofferings.Forexample,ActiveDirectoryFederationServices2(ADFS2)isaWindowsServerrolethat,amongotherthings,enablesyourActiveDirectoryinstancetoactasanidentityproviderandissueclaimsforyouruseraccounts.

WindowsIdentityFoundation(WIF)isasetofclassesandtools,anextensiontothe.NETFramework,thatenablesyoutouseclaims-basedidentitywhendevelopingASP.NETorWCFapplications.Itisseamlesslyintegratedwiththecore.NETFrameworkclassesandinVisualStudiosothatyoucankeepusingthetoolsandtechniquesyouarefamiliarwithfordevelopingyourapplications,whilereapingtheadvantagesofthenewmodelwhenitcomestoidentity.

Inthissection,IwillintroducethebasicsofWindowsIdentityFoundation:howitexposesclaims-basedidentityprinciplestodevelopers,somefundamentalconsiderationsaboutitsstructure,andtheessentialprogrammingsurfaceeverydevelopershouldbeawareof.

Page 20: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

16 Part I Windows Identity Foundation for Everybody

An API for Claims-Based IdentityIntheprevioussection,youlearnedaboutclaims-basedidentity.Ifyouhadtoexposeitasaprogrammingmodelsothatanapplicationdevelopercouldtakeadvantageofit,whatrequirementswouldyoufollow?Hereismywishlist:

■ Makeclaimsavailabletothedeveloperinaclear,consistent,andprotocol-independentfashion.

■ Takecareofall(ornearlyall)authentication,authorization,andprotocolhandlingoutsideofthecodeoftheapplication,awayfromtheeyesofthedeveloper.

■ Minimizetheneedtochangethecodewhenchangesatdeploymenttimeoccur.Driveasmuchoftheapplication’sbehavioraspossibleviaconfiguration.

■ Provideawaytoeasilyconfigureapplicationstorelyonexternalidentityprovidersforauthentication.

■ Provideawayforapplicationstoeasilyadvertisetheirrequirementsviapolicy.

■ Organizeeverythinginapluggablearchitecturethatcansupportmultipleprotocolsandisolatethedeveloperfromthedetailsofthedeployment(onpremisesandcloud,ASP.NETandWCF,andsoon).

■ Respectasmuchaspossibleexistingcodeandpractices,maximizingtheamountofoldcodethatwillstillworkinthenewmodelwhileofferingincrementaladvantageswiththenewAPIs.

Asyou’llseetimeandtimeagainthroughoutthebook,WIFsatisfiesallthesecriteria.

WIF’s Essential BehaviorEarlierinthetext,IwrotethatPartIofthebookwillshowyouhowtotakeadvantageofWIFinyourapplicationswithouttheneedtobecomeasecurityexpert,andIintendtokeepthatpromise.HereI’llstartwithasimplifieddescriptionofhowWIFworks,coveringtheessentialpointsforallowingyoutousetheproduct.PartIwillbeaboutASP.NETapplications,andI’llstickwithdiscussingscenariosthatcanbetackledbyusingWIFtoolingalone.I’llomitthedetailsthathavenoimmediateuse.YoucanrefertoPartIIofthebookifyouwanttoknowthewholestory.

WIFallowsyoutoexternalizeauthenticationandauthorizationbyconfiguringyourapplicationtorelyonanidentityprovidertoperformsomeorallthosefunctionsforyou.Howdoesitdothatinpractice?

Figure1-4showsasimplifieddiagramofhowWIFhandlesauthenticationintheASP.NETcase.

Page 21: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 17

Identity Provider

ApplicationSubject

2

31

5

4

WIF

ClaimsBrowser

STS

FIGURE1-4 AsimplifieddiagramofhowWindowsIdentityFoundationtakescareofhandlingauthenticationforanASP.NETapplication

Theideaisextremelysimpleandcloselymimicsthecanonicalclaims-basedidentitypattern:

1. WIFsitsinfrontofyourapplicationintheASP.NETpipeline.Whenanunauthenticateduserrequestsapage,itredirectsthebrowsertotheidentityproviderpages.

2. HeretheIPauthenticatestheuserinwhateverwayitchooses(perhapsbyshowingapagewithusernameandpassword,usingKerberos,orinsomeotherway).Thenitmanufacturesatokenwiththerequiredclaimsandsendsitback.

3. ThebrowserpoststhetokenitgotfromtheIPtotheapplication,whereWIFagaininterceptstherequest.

4. Ifthetokensatisfiestherequirementsoftheapplication(thatis,itcomesfromtherightIP,containstherightclaims,andsoon),theuserisconsideredauthenticated.WIFthendropsacookie,andasessionisestablished.

5. Theclaimsintheincomingtokenaremadeavailabletotheapplicationcode,andthecontrolispassedtotheapplication.

Aslongasthesessioncookieisvalid,thesubsequentrequestswon’tneedtogothroughthesameflowbecausetheuserwillbeconsideredtobeauthenticated.

Youarenotsupposedtoknowityet,buttheprecedingflowunfoldsaccordingtotheWS-Federationprotocolspecification:mostofthemagicisdonebytwoHTTPmodules:WSFederationAuthenticationModule(WSFAM)andSessionAuthenticationModule.

Page 22: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

18 Part I Windows Identity Foundation for Everybody

ThewholetrickofusingWIFinyourapplicationboilsdowntothefollowingtasks:

1. ConfiguretheapplicationsothattheWIFHTTPmodulessitintheASP.NETpipelineinfrontofit.

2. ConfiguretheWIFmodulessothattheyrefertotheintendedIPs,usetherightprotocols,protecttheplannedresourcesoftheapplication,andingeneralenforceallthedesiredapplicationpolicies.

3. Accessclaimvaluesfromtheapplicationcodewheneverthereisaneedintheapplicationlogictomakeadecisiondrivenbyuseridentityattributes.

Thegoodnewsisthatinmanycasessteps1and2canbeperformedviaVisualStudiotooling.Thereisahandywizardthatwalksyouthroughtheprocessofchoosinganidentityprovider,offersyouvariousoptions,andinformsyouaboutthekindofclaimsyoucangetabouttheuserfromthespecificIPyouarereferringto.Thewizardtranslatesalltheprefer-encesyouexpressedviapointandclickintheweb.configsettings.ThenexttimeyoupressF5,yourapplicationwillalreadyapplythenewauthenticationstrategy.Congratulations,yourapplicationisnowclaims-aware.

Thegoodnewskeepcoming;performingstep3issimpleandperfectlyinlinewithwhat.NETdevelopersarealreadyaccustomedtodoingwhenhandlinguserattributes.

IClaimsIdentity and IClaimsPrincipalRememberIIdentityandIPrincipalasameansofdecouplingtheapplicationcodefromtheauthenticationmethod?Itworkedprettywelluntilwefoundanauthenticationstyle(clientcertificates)thatbrokethemodel.Nowthatauthenticationisnolongeraconcernoftheapplication,wecanconfidentlyrevisittheapproachandapplyitforexposingnewinforma-tion(claims)byleveragingafamiliarmodel.

WIFprovidestwoextensionstoIIdentityandIPrincipal, IClaimsIdentityandIClaimsPrincipal,respectively—whichareusedtomaketheclaimsprocessedintheWIFpipelineavailabletotheapplicationcode.TheinstancesliveintheusualHttpContext.Current.UserpropertyinASP.NETapplications.YoucanusethemasiswiththeusualIIdentityandIPrincipalprogram-mingmodel,oryoucancastthemtothecorrectinterfaceandtakeadvantageofthenewfunctionalities.

Let’stakeaquicklookatthemembersofthenewinterfaces.Notethatthelistfornowisbynomeansexhaustiveandhighlightsonlypropertiesthatwillbeusefulinbasicscenarios.

Page 23: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 19

IClaimsPrincipalisdefinedasfollows:

public interface IClaimsPrincipal : IPrincipal { // ... // Properties ClaimsIdentityCollection Identities { get; } }

BecauseIClaimsPrincipalisanextensionofIPrincipal,alltheusualfunctionalities(suchasIsInRole)aresupported.Asyou’llseeinChapter2,“CoreASP.NETProgramming,”thisuse-fulpropertyextendstootherASP.NETfeaturesthattakeadvantageofIPrincipalroles—forexample,accessconditionsexpressedviathe<authorization>elementstillwork.

TheonlynoteworthynewsistheIdentitiescollection,whichisinfactalistofIClaimsIdentity.Let’stakealookatthedefinitionofIClaimsIdentity:

public interface IClaimsIdentity : IIdentity { // ... ClaimCollection Claims { get; } }

HereIstrippedoutmostoftheIClaimsIdentitymembers(becauseI’llhaveachancetointroducethemallasyouproceedthoughthebook),butIleftinthemostimportantone,thelistofclaimsassociatedwiththecurrentuser.WhatdoesaClaimlooklike?

public class Claim { // ... // Properties public virtual string ClaimType { get; } public virtual string Issuer { get; } public virtual IClaimsIdentity Subject { get; } public virtual string Value { get; } }

Onceagain,manymembershavebeenstrippedoutforthesakeofclarity.Thepropertiesshownareself-explanatory:

■ ClaimType Representsthetypeoftheclaim:birthdate,role,andgroupmembershipareallgoodexamples.WIFcomeswithanumberofconstantsrepresentingnamesofclaimtypesincommonuse;however,youcaneasilydefineyourowntypesifyouneedto.ThetypicalclaimtypeisrepresentedwithaURI.

■ Value Specifies,asyoucanimagine,thevalueoftheclaim.Itisalwaysastring,althoughitcanrepresentavalueofadifferentCLRtype.(Birthdateisagoodexample.)

Page 24: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

20 Part I Windows Identity Foundation for Everybody

■ Issuer IndicatesthenameoftheIPthatissuedthecurrentclaim.

■ Subject PointstotheIClaimsIdentitytowhichthecurrentClaimbelongs,whichisarepresentationoftheidentityofthesubjecttowhichtheclaimrefersto.

Ifyouunderstandwhataclaimis,andifyouhaveanytypeofidentitycardinyourwallet,thepropertiesjustdescribedareintuitiveandeasytouse.Let’slookatoneeasyexample.

SupposethatyouareworkingononeapplicationthathasbeenconfiguredwithWIFtouseclaims-basedidentity.Let’ssaythatauthenticationtakesplaceattheverybeginningofthesession,sothatduringtheexecutionyoucanalwaysassumetheuserisauthenticated.Atacertainpointinyourcode,youneedtosendane-mailnotificationtoyouruser.Therefore,youneedtoretrievehere-mailaddress.Herethere’showyoudoitwithWIF:

IClaimsIdentity identity = Thread.CurrentPrincipal.Identity as IClaimsIdentity; string Email = (from c in identity.Claims where c.ClaimType == System.IdentityModel.Claims.ClaimTypes.Email select c.Value).SingleOrDefault();

ThefirstlineretrievesthecurrentIClaimsIdentityfromthecurrentprincipalofthethread,exactlyasitwouldifyouwantedtoworkwiththeclassic.NETIIdentity—theonlydifferenceisthedowncasttoIClaimsPrincipal.

ThesecondlineusesLINQforretrievingthee-mailaddressfromthecurrentclaimcollection.Thequeryisveryintuitive:yousearchforalltheclaimswhosetypecorrespondstothewell-knownEmailclaimtype,andyoureturnthevalueofthefirstoccurrenceyoufind.Forthee-mailcase,itisreasonabletoexpectthattherewillbeonlyoneoccurrenceinthecollection,However,thisisnottrueinthegeneralcase.JustthinkofhowmanygroupclaimswouldbegeneratedforanygivenWindowsuser;thus,thestandardwayofretrievingaclaimsvaluemusttakeintoaccountthattheremightbemultipleclaimsofthesametypeinthecurrentIClaimsIdentity.

Nothinginthecodeshownindicateswhichprotocolorcredentialtypeshavebeenusedforauthenticatingtheuser.Thatmeansyouarefreetomakeanychangesinthewayinwhichusersauthenticate,withouthavingtochangeanythinginyourcode.RelyingononeIPforhandlinguserauthenticationandusingopenprotocolsdeliverstrueseparationofconcerns;therefore,makingthosechangesisalsoveryeasy.

Relyingonclaimsforgettinginformationabouttheusermitigatestheneedformaintainingattributestores,wherethedatacanbecomestaleorbecompromised.Asyoucanobserve,thecodeshowninthissectiondoesnotcontainanycalltoalocaldatabasethatcouldbebrokenbyroutinechangesorthatcouldbecomeaproblemiftheapplicationismovedtoanexternalhostthatcannotaccesslocalresources.Intheageofthecloud,theimportanceofbeingabletomoveapplicationsaroundcannotbeoverestimated.

Page 25: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 1 Claims-Based Identity 21

Finally,thetwolinesofcodeshownearlierwillworkwithanykindof.NETprogram,ASP.NETorWCF.ThewayinwhichWIFsnapstothetwodifferenthostingmodelsandpipelinesisdifferent.IwilldescribehowitdoesthisindetailinPartII;however,fromtheperspectiveoftheapplicationdeveloper,nothingchanges.Thetoolingoperatesitsmagicforconfiguringtheapplicationtoexternalizeauthentication.AllyouneedtoknowishowtominetheresultswithaconsistentAPIwithoutworryingaboutunderlyingprotocols,hostingmodel,orlocation.

Itwouldappearthataddingoneextralayerofindirectionworked.WefinallyfoundanAPIthatcansecureyourapplicationswithoutforcingyoutotakecareofthedetails.

SummaryTraditionalapproachestoaddingidentityandaccessmanagementfunctionalitytoapplicationsallhavethesameissues:theyrequirethedevelopertotakemattersintohisownhands,callingforspecializedsecurityknowledge,ortheyheavilyrelyonthefeaturesoftheunderlyinginfrastructure.ThissituationhasledtoaproliferationofAPIsandtechniques,forcingdeveloperstocontinuallyre-learnhowtoperformthesametaskwithdifferentAPIs.Theresultingsoftwareisbrittle,difficulttomaintain,andresistanttochange.Inthischapter,Igavesomeconcreteexamplesofhowthissystemicflawintheapproachtoaddingidentityandaccessmanagementaffectsdevelopment,evendevelopmentin.NET.

Claims-basedidentityisanapproachthatchangesthewaywethinkaboutauthenticationandauthorization,addingalogicalrepresentationofidentitytransactionsandidentifyingtherolesthateveryentityplays.Byaddingthatfurtherlevelofindirection,claims-basedidentitycreatedthebasisforthedecouplingoftheprogrammingmodelandthedetailsofdeploy-timesystems.Inthechapter,Idescribedthebasicsofclaims-basedidentityandyoulearnedhowitcanbeusedtomodelawidevarietyofscenarios.

WindowsIdentityFoundationisonesetof.NETclassesandtoolsthathelpsdeveloperstosecureapplicationsbyfollowingtheprinciplesofclaims-basedidentity.Thischapterintro-ducedtheessentialprogrammingsurfaceexposedbyWIF,anditdemonstratedhowWIFdoesnotsufferfromtheissuesImentionedfortraditionalapproaches.

Inthenextchapter,IwillshowhowtotakeadvantageofWIFforperformingauthentication,authorizationandidentity-drivencustomizationinavarietyofcommonWebscenarios.

Page 26: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

95

Chapter4

Advanced ASP .NET ProgrammingIn this chapter:More About Externalizing Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Single Sign-on, Single Sign-out, and Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112Federation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Claims Processing at the RP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Nowthatmosttechnicalitiesareoutoftheway,wecanfocusonintendedusageoftheproductforaddressingawiderrangeofscenarios.

ThischapterresumesthearchitecturalconsiderationsthatdrovePartIofthebook,“WindowsIdentityFoundationforEverybody,”bytacklingmorecomplexsituations.I’llassumeyouarenowfamiliarwiththeflowdescribedinChapter3,“WIFProcessingPipelineinASP.NET.”I’llgiveyouconcreteindicationsabouthowtocustomizethedefaultbehaviorofWindowsIdentityFoundation(WIF)toobtainthedesiredeffectforeverygivenscenario.

Usingclaims-basedidentityinyourapplicationis,forthemostpart,theartofchoosingwhotooutsourceauthenticationtoandprovidingjusttherightamountofinformationforinfluencingtheprocess.ThischapterwillnotexhaustallthepossiblewaysyoucancustomizeWIF—farfromit.However,itwillequipyouwiththeprinciplesyouneedtoconfidentlyexplorenewscenariosonyourown.

Thefirstsection,“MoreAboutExternalizingAuthentication,”takesadeeperlookattheentitiestowhichyoucanoutsourceauthenticationforyourapplication.I’llgobeyondthesimplificationsofferedsofar,introducingtheideaofmultipleprovidertypes.Alotofthediscussionwillbeatthearchitecturallevel,helpingyouwiththedesignchoicesinyoursolutions.However,hardcorecodersshouldnotfear!ThesectionalsodivesdeepintotheSecurityTokenService(STS)projecttemplatethatcomeswiththeWIFSDK.Althoughinrealscenariosyou’llrarelyneedtocreateacustomSTS,giventhatmoreoftenthannotyou’llrelyonoff-the-shelfproductssuchasActiveDirectoryFederationServices2.0(ADFS2.0),you’llfinditusefultoseeaconcreteexampleofhowthearchitecturalconsiderationsmentionedarereflectedincode.

The“SingleSign-on,SingleSign-out,andSessions”sectionexplorestechniquesthatreducetheneedforuserstoexplicitlyentertheircredentialswhenvisitingaffiliatedWebsitesand

Page 27: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

96 Part II Windows Identity Foundation for Identity Developers

showshowtocleanupmultiplesessionsatonce.Onespecificcase,sessionswithslidingvalidity,istheoccasionforadeeperlookathowWIFhandlessessions.

The“Federation”sectiondissectsthepatternthatismostwidelyusedforhandlingaccessacrossmultipleorganizations.I’llcovermoreindepththeuseofSTSesforprocessingclaims,andwe’lltackletheproblemofdecidingwhoshouldauthenticatetheuserwhentherearemanyidentityproviders(IPs)tochoosefrom(somethingknownasthehome realm discovery problem).Thesolutionstothoseproblemscanbeeasilygeneralizedtoanysituationinwhichtherelyingparty(RP)—whichwasdiscussedinChapter3—needstocommunicateoptionstotheIP.I’lldemonstratethatwithanotherexample:theexplicitrequestforacertainauthenticationlevel.

The“ClaimsProcessingattheRP”sectionclosesthechapterbydescribinghowtouseWindowsIdentityFoundationforpreprocessingtheclaimsreceivedfromtheidentityprovider.I’llbrieflyrevisittheclaims-basedauthorizationflow—introducedinminimaltermsinChapter2,“CoreASP.NETprogramming.”ThenI’llshowyouhowtofilterandenrichtheIClaimsPrincipalbeforetheapplicationcodegainsaccesstoit.

Afteryoureadthischapter,you’llbeabletomakeinformeddecisionsabouttheidentitymanagementarchitectureofyoursolutions.You’llknowwhatittakestoimplementsuchdecisionsinASP.NET.You’llhaveconcreteexperienceusingtheWIFextensibilitymodelforsolvingarangeofclassicidentitymanagementscenarios.ThatexperiencewillhelpyoutodeviseyourownWIF-basedsolutions.Onceagain,I’llgiveyoupracticalcodeindicationsabouttheASP.NETcase,butthegeneralprinciplesintroducedherecanbeappliedmorebroadly,oftentotheWCFservicescaseandevenonnon-Microsoftplatforms.

MoreAboutExternalizingAuthenticationUntilnow,Ihavedescribedsituationsinwhichtheapplicationreliesononlyoneexternalentity—whatIdefinedastheidentity provider,orIP.Althoughthisisanaccuraterepresenta-tionofaparticularcommonscenario,thegeneralcasecanbeabitmorecomplicated.Notonlymightyouhavetoacceptidentitiesfrommultipleidentityproviders,identityprovidersarenottheonlyentitiesyoucanoutsourceauthenticationto!

Sofar,theroleplayedbytheentitywithinatransaction(theidentityprovider)hasbeenconflatedwiththeinstrumentusedtoperformthefunction(theSTS).Thepurposeofthissectionistohelpyoubetterunderstandtheseparationbetweenthetwobyprovidingmoredetailsaboutthenatureoftheidentityprovider,introducinganewroleknownasthefederation provider,andstudyinghowthosehigh-levelfunctionsreflectontheimplementationoftheassociatedSTS.

Page 28: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 97

Identity ProvidersBeinganidentityproviderisarole,ajobifyouwill.YouknowfromChapter1,“Claims-BasedIdentity,”thatanIP“knowsaboutsubjects.”Infact,allthethinkingbehindtheideaofIPisjustgoodserviceorientationappliedtoidentity.

Thestandardexampleofaconcreteidentityproviderisonebuiltontopofadirectory,justasADFS2.0isbuiltontopofActiveDirectory.Inthisscenario,there’sanentitythatiscapableofauthenticatingusersandmakingassertionsaboutthem,andallyouaredoingismakingthatcapabilityreusabletoawideraudiencebyslappingastandardfaçade(theSTS)infrontofit.TheuseofstandardswhenexposingtheSTSissimplyawayofmaximizingtheaudienceandincreasingreusability.Here’sanexample:AlthoughaSharePointinstanceonanintranetcantakeadvantageofActiveDirectoryauthenticationcapabilitiesdirectlyviaKerberos,thatisnotthecaseforaSharePointinstancelivingoutsidethecorporateboundariesandhostedbyadifferentcompany.ExposingtheauthenticationcapabilitiesofActiveDirectoryviaADFS2.0makesitpossibletoreuseidentitieswiththeSharePointinstanceinthesecondscenario,removingtheplatformandlocationconstraints.WIFisjustmachinerythatenablesyourapplicationtotakeadvantageofthesamemechanism.ItisworthwhiletopointoutthatSharePoint2010is,infact,basedonWIF.

Anotheradvantageofwrappingtheactualauthenticationbehindastandardinterfaceisthatyouarenowisolatedfromitsimplementationdetails.TheIPcouldbeafaçadeforadirectory,amembershipprovider–basedsite,oranentirelycustomsolutiononanarbitraryplatform;aslongasitsSTSexposestheauthenticationfunctionalitythroughstandards,applicationscanuseitwithouttiesordependenciesoutsideoftheestablishedcontract.Whocaresiftheconnectionstringtothemembershipdatabasechanges,orevenifthereisamembershipdatabaseinthefirstplace?AllyouneedtoknowistheaddressoftheSTSmetadata.

ThosecharacteristicsoftheIProletellyouquitealotaboutwhattoexpectregardingthestructureoftheSTSexposedbyoneIP.

Note Inliterature,you’lloftenfindthatoneSTSusedbyoneIPcanbedefinedasan“IP-STS.”Inashort,you’llseehowthiscansometimesbeusefulfordisambiguatingthefunctiontheSTSoffers.

IntheWS-FederationSign-inflow,describedinChapter3,yousawthatthedetailsofhowtheSTSauthenticatestherequestforsecuritytokensisaprivatematterbetweentheSTSandtheuser.NowyouknowthatsuchasystemhastobesomethingthatallowstheSTStolookupuserinformationfromsomestore—sothatitcanbeextractedandpackagedintheformofclaims.NotableexamplesaretheonesinwhichtheSTSleveragesthesameauthenticationmethodsoftheresourceitiswrapping.IftheIPisafaçadeforActiveDirectoryandtheuser

Page 29: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

98 Part II Windows Identity Foundation for Identity Developers

isontheintranet,theSTSmightverywellbehostedononeASPXpagethatisconfiguredinInternetInformationServices(IIS)toleverageWindowsnativeauthentication.Ifthesourceisamembershipdatabase,theSTSsitewillbeprotectedviaamembershipprovider,andsoon.Theclaimvalue’sretrievallogicintheSTSwillusewhatevermonikertheauthenticationschemeoffersforlookingupclaimvalues,buttheauthenticationwilloftenbeperformedbytheinfrastructurehostingtheSTSratherthantheSTScodeitself.

NothingpreventsoneIPfromexposingmorethanoneSTSendpointtoaccommodatemultipleconsumptionmodels.Forexample,thesameIPmightbelisteningforKerberosauthenticatedrequestsfromtheintranetandX.509securedcallsonanendpointavailableontheInternet;theIPmightexposefurtherendpoints,bothforbrowser-basedrequestorsviaWS-FederationandSAMLPorforactiverequestorsviaWS-Trust;andsoon.ThisprocessoffersanotherinsightintohowoneIPisstructured:authenticationandclaimsissuancelogicshouldcommunicatebutremainseparatesothatmultipleSTSendpointsscenariosarehan-dledwithlittleornoduplication.Asyou’llseelaterinthesection,theWIFSTSprogrammingmodelisconsistentwiththatconsideration.

AnIPwillactivelymanagethelistoftheRPsitiswillingtoissueatokenfor.Thisisnotonlyamatterofensuringthatclaimsaretransmittedexclusivelytointendedrecipients,butalsoapracticalnecessity.Especiallyinthepassivecase,inwhichtokenrequestsareusuallysimple,theIPdecideswhatlistofclaimswillbeincludedinatokenaccordingtotheRPthetokenisbeingissuedfor.(“Passivecase”ismainlyanotherwaytosaythatyouuseabrowser.You’llknoweverythingaboutitafterreadingChapter5,“WIFandWCF.”)SuchalistisestablishedwhentheRPisprovisionedintheIP’sallowlist.JustlikeWIFenablesoneapplicationtoes-tablishatrustrelationshipwithanIPbyconsumingitsmetadataviatheFederationUtilityWizard,IPsoftwaresuchasADFS2.0includeswizardsthatcanconsumetheapplicationmetadataandautomaticallyprovisiontheRPentryinitsallowlist.

Note Incomputerscienceasinotherdisciplines,anallowlistisalistofentitiesthatareapprovedtodosomethingortoberecipientsofsomeaction.Forexample,ifyourcompanynetworkhasanallowlistofWebsites,thatmeansyoucanbrowseonlyonthosesitesandnoother.Conversely,havingablacklistofWebsitesmeansthatyoucanbrowseeverywherebutonthose.AnIPnormallymaintainsanallowlistofRPsitiswillingtoissueatokenfor:anyrequestforarecipientnotintheallowlistisrefused.TheADFS2.0UIdescribesthatasRelying Party Trust.Iamnotveryfondofthatuseof“trust,”whichinthiscontexthasaspecialmeaning(be-lievingthattheclaimsissuedbyagivenIPaboutasubjectaretrue),butyourmileagemayvary.

TheIPalsokeepstrackofthecertificateassociatedwiththeRP,bothforensuringthattheRPhasastrongendpointidentity(exposedviaHTTPS)andforencryptingthetokenwiththecorrectkeyifconfidentialityisrequired.

Page 30: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 99

NonauditingSTSTherearesituations,especiallyintheareaofe-government,inwhichtheuserwouldliketokeepprivatetheidentityoftheRPheisusing.Forexample,acitizenmightwanttouseatokenissuedbyagovernmentIPprovinghisage,butatthesametimehewouldliketomaintainhisprivacyaboutwhatkindofsites(forexample,liquormerchants)heisusingthetokenfor.

Technically,thescenarioispossible,althoughsettingupsuchfunctionalitywouldintroducesomelimitations.Forexample,notknowingtheidentityoftheRP,theIPwouldnotknowtheassociatedX.509certificateandthatwouldmakeitimpossibletoencrypttheissuedtoken.Also,someprotocolshandlethescenariobetterthanothers.AlthoughtheWS-Federationspecificationallowsforspecifyingwhichclaimsshouldbeincludedintherequestedtoken,mostimplementationsexpectthelistofclaimsrequiredbyoneRPtobeestablishedapriori,whichisofcourseofnohelpiftheidentityoftheRPisnotknown.ThingscanbealittleeasierwithWS-Trust,asyou’llseeinthenextchapter.

Inthebusinessworld,themostcommonscenariorequirestheIPtohaveapreexistingrelationshipwiththeRPbeforeissuingtokensforit;therefore,off-the-shelfproductssuchasADFS2.0normallymandateit.

Thescenariodescribedsofar—oneapplicationoutsourcingauthenticationtooneidentityprovider—iscommon,andnoneofthefurtherdetailsaboutIPsIgavehereinvalidateit.However,sometimestheplanetsdonotalignthewayyou’dlike,andforsomereasonsimpledirectoutsourcingtooneIPdoesnotsolvetheproblem.

Federation ProvidersLet’sconsiderforamomentthematterofhandlingmultipleidentityproviders.Imaginebeingadeveloperforafinancialinstitution.Let’ssayyouarewritingacorporatebankingapplication,whichallowscompaniestohandlethesalarypaymentprocessfortheirwork-force.Thisisclearlyonecaseinwhichyouneedtotrustmultipleidentityproviders—namely,allthecompanieswhoaccessyourfinancialinstitutionformanagingpayments.

Fromwhatyouhaveseensofar,youknowonlyonewayofhandlingthesituation:addingmultipleFederatedPassiveSignIncontrolstoyourapplicationentrypage,eachofthempointingtoadifferentidentityprovider.Althoughtheapproachworks,itcanhardlybecalledafullexternalizationofidentitymanagementbecauseprovisioninganddeprovisioningidentityprovidersforcesyoutochangetheapplicationcode.Thingsgetworsewhenyouhaveoneentireportfolioofapplicationstomakeavailabletoalistofmultipleidentityproviders—havingtoreapplythetrickmentionedpreviouslyforeveryapplicationrapidly

Page 31: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

100 Part II Windows Identity Foundation for Identity Developers

becomesunsustainableasthenumberofappsandIPsgoesup.ThisclearlyindicatestheneedtofactoroutIPrelationshipmanagementfromtheapplicationresponsibilities.

Anothercommonissueyoumightencounterhastodowiththeabilityofyourapplicationtounderstandclaimsasissuedbyoneidentityprovider.Hereiswhy:

■ Sometimesyoumighthavesimpleformatissues.Forexample,theusersyouareinterestedinmightcomefromanothercountryandtheirIPmightuseclaimURIscontaininglocale-specifictermsyourapplicationdoesnotunderstand.(AnEnglishapplicationmightneedtoknowthenameofthecurrentuserandexpectitinanhttp://claims/nameformat,whileanItalianIPmightsendthedesiredinformationinthehttp://claims/nomeclaimformat.)

■ Sometimestheinformationwillneedsomeprocessingbeforebeingfedtoyourapplication.Forexample,anIPmightofferabirthdateclaim,butyourapplicationmightbeforbiddenfromreceivingpersonallyidentifiableinformation(PII).AllyourequirehereisasimpleBooleanvalueindicatingiftheuserisbeloworaboveacertainthresholdage.AlthoughtheinformationisclearlyavailabletotheIP,itmightnotbeofferedasaclaim.

■ Finally,youmightneedtointegratetheclaimsreceivedfromtheIPwithfurtherinformationthattheIPdoesnotknow.Forexample,youmightbeanonlinebookshopacceptingusersfromapartnerIP.TheIPcanprovideyouwithnameandshippingaddressclaims,butitcannotprovideyouwiththelast10bookstheuserboughtfromyourstore.Thatisdatathatbelongstoyou,andyouhavetheresponsibilityofmakingitavailableintheformofclaimsifyouwanttooffertoyourdevelopersaconsistentwayofconsumingidentityinformation.

Whatisneededhereisameansofdoingsomepreprocessing—somekindofintermediarythatcanmassagetheclaimsandmakethemmoredigestiblefortheapplication.

Thestandardsolutiontotheseissuesistheintroductionofanewroleinidentitytransactions,whichgoesbythenameofFederationProvider(FP).

AFederationProviderisaclaimstransformer;itisanentitythatacceptstokensininput—kindoflikeanRPdoes—andissuestokensthatare(usually)theresultofsomekindofprocessingoftheinputclaims.AnFPoffersitstokenmanipulationcapabilitiesexactlylikeanIP,byexposingSTSendpoints.Themaindifferenceisthat,whereasoneIPusuallyexpectsre-questsforsecuritytokenssecuredbyusercredentialsthatwillbeusedforlookingupclaims,theFPexpectsrequeststobesecuredwithanissuedtokenthatwillbeusedasinputfortheclaimstransformationprocess.IntheIPcase,theissuedtokencontainstheclaimsdescribingtheauthenticateduser;intheFPcase,theissuedtokenistheresultoftheprocessingappliedtothetokenreceivedintherequest.GiventhefactthatanFPexposesoneSTS,applicationscanuseitforexternalizingauthenticationinexactlythesamewayasyouhaveseentheydowithIPs.WIF’sFederationUtilityWizarddoesnotdistinguishbetweenIPsandFPs—allitneedsisanSTSanditsmetadata.

Page 32: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 101

Thereasonthatit’sknownastheFederationProvideristhatenablingfederationistheprimarypurposethatledtotheemergenceofthisrole.Inanutshell,here’showthatworks.ImaginecompanyAisamanufacturerthathasanumberofline-of-business(LOB)applica-tionsforitsownemployees,includingapplicationsforsupplymanagement,inventory,andotherusualstuff.CompanyBisaretailerthatsellstheproductsmanufacturedbyA.Toim-provetheefficiencyoftheircollaboration,AandBdecidetoenterintoafederationagree-ment:certainBemployeeswillhaveaccesstocertainAapplications.InsteadofhavingeveryAapplicationaddtheBidentityproviderandhavingtheBIPprovisioneveryapplicationasarecognizedRP,AexposesaFederationProvider.

TheBIPwillprovisiontheAFPjustlikeanyotherRP,associatingtotherelationshipthelistofclaimsthatBdecidestosharewithAaboutitsusers.AlloftheAapplicationsthatneedtobeaccessiblewillenterintoatrustrelationshipwiththeAFP,outsourcingtheirauthenticationmanagementtoitsSTS.Figure4-1showsthetrustrelationshipsandthesign-inflow.

Browser

IP-STS

APP

1

23 4

6

7

Trust

Trust

R-STS

5

IP FP

B A

A

AB

B

FIGURE4-1 Theauthenticationflowinafederationrelationshipbetweentwoorganizations

Theflowgoesasfollows:

1 OneemployeeofBnavigatestooneapplicationinA.

2 TheuserisnotauthenticatedbecausetheapplicationwillacceptonlyuserspresentingtokensissuedbytheAFP.TheapplicationredirectstheusertotheAFP.

3 Again,theuserisnotauthenticated.TheAFPwillacceptonlyuserspresentingtokensissuedbytheBIP.TheapplicationredirectstheusertotheBIP.

4 TheuserlandsontheBIP,whereauthenticationwilltakeplaceaccordingtothemodesdecidedbyB.TheusergetsatokenfromtheBIP.

5 TheusergetsbacktotheAFPandpresentsthetokenfromtheBIP.

Page 33: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

102 Part II Windows Identity Foundation for Identity Developers

6 TheAFPprocessesthetokenaccordingtotheapplication’sneeds—someclaimsmightbereissuedverbatimastheywerereceivedfromB;othersmightbesomehowprocessed;stillothersmightbeproducedandaddedanew.TheAFPpackagestheresultsoftheprocessingintheformofclaimsandissuesthenewtokentotheuser.

7 TheusergetsbacktotheapplicationandpresentsthetokenfromtheAFP;theapplicationauthenticatesthecallbyexaminingthetokenfromAFP.

ThemainadvantageofusinganFPinafederationscenarioisobvious:younowhaveasingleplacewhereyoucanmanageyourrelationship,definingitsterms(suchaswhichclaimsyoushouldreceive).Theapplicationsaredecoupledfromthosedetails.BecausetheFPknowsaboutboththeincomingclaims(becauseitisonpointforhandlingtherelationships)andtheclaimsneededbytheapplication(becauseitispartoftheorganization,itknowsaboutwhichclaimtypesareavailableandtheirsemantics),applicationscaneffectivelytrustittohandleauthenticationontheirbehalfeveniftheactualusercredentialsverificationtakesplaceelsewhere.Theprocesscanbeiterated.Forexample,youcanhaveanFPtrustinganotherFP,whichinturntrustsanIP,althoughthatdoesnothappentooofteninpractice.

The WIF STS TemplateOutsourcingauthenticationtooneexternalSTSmakeslifemucheasierfortheapplicationdeveloper,atthepriceofrelinquishingcontrolofakeysystemfunctiontotheSTSitself.Althoughrelinquishingcontrolofthemechanicsofauthenticationissweet,asI’vebeenpointingoutthroughtheentirebook,theSTSyouchoosebetterbegood,orelse.Here’swhatImeanby“good”inthiscase:

■ AnSTSmustbesecure AcompromisedSTSisanabsolutecatastrophebecauseitcanabuseyourapplication’strustbymisrepresentingtheuserprivileges.

■ AnSTSmustbeavailable IftheSTSendpointisdown,asaconsequenceofpeaktrafficoranyotherreason,yourapplicationisunreachable:notoken,noparty.

■ AnSTSmustbehigh-performing Everytimeauserbeginsasessionwithyourapplication,theSTScomesintoplay.Badperformanceisextremelyvisible,canbecomeasourceoffrustrationforusers,andevenpileuptocompromisethesystem’savailability.

■ AnSTSmustbemanageable IfyouowntheSTS,whetheritusedasanIPorFP,you’llneedtomanagemanyaspectsofitsactivitiesandlifecycle,suchasthelogicusedforretrievingclaimvalues,provisioningofrecognizedRPs,establishmentoftrustrelationshipswiththeIPoffederatedpartners,managementofsigningandencryp-tionkeys,auditingoftheissuingactivities,andmanagementofmultipleendpointsfordifferentcredentialtypesandprotocols.Thelistgoesonandon.

Page 34: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 103

Inotherwords,runninganSTSisseriousbusiness:don’tletanybodyconvinceyouotherwise.AnendpointthatunderstandsWS-Federation,WS-Trust,orSAMLPrequestsandcanissueatokenaccordinglytechnicallyfitsthedefinitionof“STS,”butprotocolcapabilitiesalonecan’thelpwithanyoftherequirementsjustmentioned.

Thisiswhyinthevastmajorityofreal-worldscenariositiswisetorelyonoff-the-shelfSTSproducts,suchasADFS2.0.ThoseproductshostSTSendpointsandadvancedmanagementfeaturesthatsimplifybothsmallandlargemaintenanceoperationsthatrunninganIPoranFP(orboth)entails.Let’stakeADFS2.0asanexample:ADFS2.0isatrueWindowsserverrole—tried,stressed,andtestedjustlikeanyotherWindowsserverfeature.

TheWindowsIdentityFoundationSDKmakesthegenerationofanSTSdeceivinglysimplebyofferingMicrosoftVisualStudiotemplatesforbothASP.NETWebsitesandWCFservicesprojectsthatimplementabare-bonesSTSendpoint(forWS-FederationandWS-Trust,re-spectively).TheGenerateNewSTSoptionintheAddSTSReferenceWizardjustinstantiatesoneofthosetemplatesinthecurrentsolution.ThosetestSTSesareanincrediblyusefultoolfortestingapplications,thankstothenearabsenceofinfrastructurerequirements(ADFS2.0requiresaworkingActiveDirectoryinstance,SQLServer,WindowsServer2008R2,andsoon)andinstantaneouscreation.AssomebodywhohadtowriteSTSesfromscratchwithWCFinthepast(alongandmessybusiness),IamdelightedbyhoweasyitistogenerateatestSTSwithWIF.Forthesamereason,suchtestSTSesareconsistentlyusedinWIFsamplesandcourseware.Thisbookisnoexception.

WhydoIsay“deceivinglysimple”?BecauseofalltherequirementsIlistedearlier.WIFcancertainlybeusedtobuildanenterprise-classSTS—ithasbeenusedforbuildingADFS2.0itself.However,betweentheSTStemplateofferedbytheWIFSDKandADFS2.0,therearemany,manyman-yearsofdesign,enormousamountsofdevelopmentandtesting,tonsofassumptionsanddefaultchoices,brutalfuzzing,relentlessstressing,andsoon.ThefactthattheSTStemplategivesyoubackatokendoesnotmeanitcanbeusedasisinareal-lifesys-tem.PeopleregularlyunderestimatetheeffortrequiredforbuildingaviableSTS,anerrorofjudgmentthatcanresultinseriousissues.ThatiswhyIalwaysdiscouragethecreationofcus-tomSTSesunlessit’sabsolutelynecessary,andthere’snotalotofdetailedguidanceonthat.

NowthatI’vegotthedisclaimeroutoftheway:thischapterwillusealotofcustomSTSes.TakingapeekinsideanSTSisapowerfuleducationaltoolthatcanhelpyouunderstandscenariosendtoend.BeingabletoputtogethertestSTSescanhelpyousimulatecomplexsetupsbeforecommittingresourcestothem.Finally,you’lllikelyencountersituationsinwhichsettingupacustomSTSisthewaytogo—forexample,ifyourusercredentialsarenotstoredinActiveDirectory.Theguidancehereisabsolutelynotenoughforhandlingthetask—thatwouldinvolveteachinghowtobuildsecure,scalable,manageable,andperform-ingservices,whichiswellbeyondthescopeofthistext—butitcanbeastartingpointforunderstandingthetokenissuancemodelofferedbyWIF.

Page 35: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

104 Part II Windows Identity Foundation for Identity Developers

TherestofthesectiondescribestheSTStemplateforASP.NETofferedbyWIFSDK4.0.Asyoureadthroughthissection,IsuggestyougobacktothesimpleexampleyoucreatedinChapter2andputbreakpointsonthepartsoftheSTSprojectbeingdiscussed.Everytimesomethingisnottooclear,tryatestruninthedebuggertogetabettersenseofwhat’sgoingon.

Structure of the STS ASP .NET Project TemplateTheASP.NETSecurityTokenServiceWebSitetemplate,asWIFSDK4.0namesit,canbefoundintheC#WebsitestemplateslistinVisualStudio.Asmentioned,thisisalsothetemplatethatisusedbytheAddSTSReferenceWizardforgeneratinganSTSprojectwithinanexistingsolution.Figure4-2showsthelistoftemplatesinstalledbytheWIFSDK4.0.

FIGURE4-2 ThetemplatesinstalledbyWIFSDK4.0,withthetemplateusedforcreatinganASP.NETSTShighlighted

TheSTSWebsiteistypicallycreatedonthelocalIIS.AlthoughitispossibletousetheplainHTTPbinding,ingeneraltheSTSWebsitewillbecreatedonanHTTPSendpoint.

Note UsingHTTPinthiscaseisnormallyareallybadidea.Evenifyouencryptthetokensyouissue,andeveniftheRPcantakestepsformitigatingtheriskofacceptingstolentokens,therealityisthatusingplainHTTPonbrowser-basedscenariosmakesyouvulnerabletoman-in-the-middleandotherattacks.InChapter5,you’llhaveachancetodigdeeperintothetopic.

Page 36: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 105

IISvs.VisualStudioBuilt-inWebServerVisualStudioallowsyoutodevelopWebsiteswithoutrequiringthepresenceofIISonyourdevelopmentmachine.VisualStudiooffersabuilt-inWebserver,calledtheASP.NETDevelopmentServer,whichcanbeusedtorenderpagesdirectlyfromthefilesystem.

AlthoughyoucangetWIFtoworkonWebsitesrunningontheASP.NETDevelopmentServer,therearelimitations(forexample,thebuilt-inWebserverdoesnotsupportHTTPS)andcomplications(forexample,thedynamicallyassignedportschangethesiteURIsandthusforcechangesintheconfiguration).Becauseofthis,it’sjustsimplertouseIIS.

SimilarconsiderationsledmetouseWebsiteprojectsratherthanWebapplicationones.Webapplicationdevelopmentstartsonthefilesystemandrequiresextrastepsforhosting(anddebugging)theapplicationinIIS.Furthermore,atthetimeofthiswriting,Fedutil.exeisnotabigfriendofthedynamicportssystemfeaturedbyASP.NETDevelopmentServer.TheAddSTSReferenceWizardwillnotalwaysworkasexpectedwhenlaunchedonaWebapplicationproject.

Figure4-3showsthestructureoftheSTSproject.

FIGURE4-3 TheASP.NETSTSprojectstructure

ThatisthestructureofaminimalWebsiteprotectedviaFormsauthentication,containingtheclassicLogin.aspxandDefault.aspxpages.Theweb.configfileisminimal,containingprac-ticallynothingspecifictoWIFapartfromthereferencetoitsassemblyandafewvaluesinthe<appSettings>.TheWebsiteisconfiguredtouseFormsAuthentication.AsyousawinthefirstexampleinChapter2,Login.aspxdoesnotactuallyverifyanycredentialsandrepresents

Page 37: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

106 Part II Windows Identity Foundation for Identity Developers

justapro-formaauthenticationpage:thepagewilljustcreatetheauthenticationcookieandstartasessionregardlessofthecredentialsenteredintheUI.

The hands-on lab Web Sites and Identity (C:\IdentityTrainingKit2010\Labs\WebSitesAndIdentity\Source\Ex1-ClaimEnableASPNET) exercise 2, shows how to use an existing Membership store for authenticating calls to the STS, and how to source claim values from a Role provider.

AllthisemphasizeswhatImentionedearlierabouttheseparationbetweentheSTSfunctionsandtheauthenticationmechanism:hereFormsauthenticationisthemethodofchoice,butitisindependentfromwhatWIFdoesforimplementingthetoken-issuingfunctionality.TheauthenticationsystemcouldbeeasilysubstitutedwithWindowsintegratedauthenticationorwhateverelse,aslongasittakescareofauthenticatingtheuserbeforegivingaccesstoDefault.aspx.

Note AnobviousobservationisthattheSTStemplategeneratesanIP-STS,somethingthatauthenticatesusersandissuestokensdescribingthem.ItisnothardtotransformitintoanR-STS:youcanjustruntheAddSTSReferenceWizardontheSTSprojectitself,andthatwillbeenoughforexcludingthecurrentFormsauthenticationsettingsandexternalizeauthenticationtothesecondSTSofyourchoosing.However,thatwouldchangeonlythewayauthenticationishandled,notthewayclaimsaregenerated:anR-STStransformsincomingclaims,butthedefaulttemplateimplementationdoesnotdothat.Attheendofthesection,I’lldiscusswhatyouneedtochangeformodifyingtheclaimissuancecriteriaaswell.

TheDefault.aspxpagerepresentstheSTSendpoint,andittakescareofinstantiatingandexecutingthetoken-issuinglogicinthecontextofanASP.NETrequest.Thepageitselfdoesnotcontainmuch.WhatweareinterestedinisthePage_PreRenderhandlerinDefault.aspx.cs:

public partial class _Default : Page { /// <summary> /// Performs WS-Federation Passive Protocol processing. /// </summary> protected void Page_PreRender( object sender, EventArgs e ) { string action = Request.QueryString[WSFederationConstants.Parameters.Action]; try { if ( action == WSFederationConstants.Actions.SignIn ) { // Process signin request. SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri( Request.Url ); if ( User != null && User.Identity != null && User.Identity.IsAuthenticated ) {

Page 38: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 107

SecurityTokenService sts = new CustomSecurityTokenService( CustomSecurityTokenServiceConfiguration.Current ); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest (requestMessage, User, sts ); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse (responseMessage, Response ); } else { throw new UnauthorizedAccessException(); } } else if ( action == WSFederationConstants.Actions.SignOut ) { // Ignore the rest for now // ... } }

ThiscodeistheSTScounterpartoftheWS-FederationprocessinglogicthatWIFprovidesforRPs,asstudiedinChapter3.WhereastheRPgeneratestherequestforasecuritytokenandvalidatesit,theSTSlistenstothoserequestsandissuestokensaccordingtotheWS-Federationprotocol.Here’saquickexplanationofwhatthemethoddoes:

■ ThehandlerinspectstherequestQueryStringfortheWS-Federationactionparameter,wa.Let’sfocusonthecaseinwhichwaispresentandhasthevaluewsignin1.0,whichindicatesarequestforatoken.(We’llexplorethesign-outcaselaterinthechapter.)

■ ThecodecreatesanewSignInRequestMessagefromtherequest—thatis,aname-valuecollectionthatsurfacesthevariousWS-Federationparametersasproperties.

■ Doyouhaveanon-emptyIPrincipal?Isthecurrentuserauthenticated?Ifitisn’t,anUnauthorizedAccessExceptionisthrownandtheuserisredirectedtotheloginpage.Ifitis,thefollowingmusttakeplace:

❑ GetaninstanceofSecurityTokenServicebyretrievinganinstanceofasubclass,CustomSecurityTokenService.ThisclasscontainsthecoreSTSlogic,asyou’llseeinamoment.

❑ ThenewSTSinstance,alongwiththeincomingSignInRequestMessageandtheuser’sIPrincipal,isfedtoFederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest,whereitwillbeusedforissuingthetokenandproducingasuitableSignInResponseMessage.

❑ Finally,FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponsewritestheSignInResponseMessageintheresponsestream,whichwillbeeventuallyforwardedtotheRPandprocessedasyousawinChapter3.

Page 39: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

108 Part II Windows Identity Foundation for Identity Developers

Therearealotofclasseswithlongnames,butintheendthecodeshownearlierjustfeedstheauthenticateduserandtherequesttoacustomSecurityTokenServiceclassandsendsbacktheresult.TheSTSprojectfeaturesanApp_Codefolder,whichcontainsalltheclassestheSTSneeds,includingtheCustomSecurityTokenServiceclass;allyouneedtodoistakealookatwhathappensthere.

TheRedirectExceptionintheSTSTemplateinVisualStudio2010Atthetimeofthiswriting,theASP.NETSTStemplateexhibitsasmallissuewithVisualStudio2010.AttheendofthePage_PreRendermethod,thereisacatchclausethathandlesgenericExceptionsandre-throwsthemafterhavingaddedamessage.Unfortunately,thecodedescribedearliercontainsatleastaredirect,whichthrowsanexception.Normally,youwouldnotseeit,butthere-throwmakesVisualStudiostopattheunhandledexception.Therearevariousworkaroundsforthisissue.YoucouldcatchThreadAbortExceptionandignoreit.YoucouldjustpressF5again,andtheappli-cationwillmoveforwardwithoutissues.Youcouldcommentthatlineinthetemplate.Youcouldstartwithoutdebugging.IdonotsuggestdisablingtheVisualStudiodefaultbehaviorofstoppingatunhandledexceptionsunlessyouknowverywellwhatyouaredoing.

STS Classes and Methods in App_CodeTheCommon.csfileisnotveryinteresting;it’sjustabunchofconstants.CertificateUtil.csisnotthatremarkableeither;it’sahelperclassforretrievingX.509certificatesfromtheWindowsstores,althoughthereisaninterestingpieceoftriviaforit.WIFusesthatcode,insteadoftheclassicX509Certificate2Collection.FindbecausethelatterdoesnotcallResetonthecertifi-catesitopened.

CustomSecurityTokenServiceConfiguration,asthenameimplies,takescareofstoringsomekeyconfigurationsettingsfortheSTS:thename,thecertificatethatshouldbeusedforsigningtokens,serializersforthevariousprotocols,andsoon.ThemostimportantsettingitstoresisthetypeofthecustomSecurityTokenServiceitself.

Finally,wegettotheveryheartoftheSTS:theclassinCustomSecurityToken.cs.ThecodegeneratedbythetemplatehasthepurposeofdoingthebareminimumforobtainingaworkingSTS;hence,Iwon’tanalyzeittoocloselyhere,exceptforpointingoutsomenotablebehavior.Rather,I’lluseitasabasefortellingyouaboutthemoregeneralmodelthatyouhavetofollowwhendevelopingacustomSTSinWIF.NotethattheconsiderationsaboutSecurityTokenServiceapplybothtoASP.NETandWCFSTSes.

SecurityTokenService InWIF,acustomSTSisalwaysasubclassofSecurityTokenService,andtheASP.NETtemplateisnoexception.Theclaims-issuanceprocessisrepresentedbyaseries

Page 40: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 109

ofSecurityTokenServicemethods,whichareinvokedfollowingaprecisesyntaxthatleadstheformrequestvalidationtoemitthetokenbits.Completecoverageofthatsequenceisbe-yondthescopeofthisbook;however,hereI’lllistthemainmethodsyoushouldknowabout:

❑ ValidateRequest ThismethodtakesinaRequestSecurityTokenandverifiesthatitisinarequestthatcanbehandledbythecurrentimplementation.Forexample,itchecksthattherequiredtokentypeisknown.SecurityTokenServiceprovidesanimplementa-tionofValidateRequest.YoushouldoverrideitonlyifyouareaddingorsubtractingfromthedefaultSTScapabilities.TherearealsofewthingstakingplaceinGetScopethatcouldperhapsbedoneinValidateRequest.I’llpointthoseoutasweencounterthem.

❑ GetScope GetScopeisanabstractmethodinSecurityTokenServicethatmustbeoverriddeninanyconcreteimplementation.IttakesasinputtheIClaimsPrincipalofthecallerandthecurrentRequestSecurityToken.

ThepurposeofGetScopeistovalidateandestablishsomekeyparametersthatwillinfluencethetoken-issuanceprocess.ThoseparametersaresavedinoneinstanceofScope,whichisreturnedbyGetScopeandwillcascadethroughallthesubsequentmethodsinthetoken-issuancesequence.HerearethemainquestionsthatGetScopeanswers:

❑ Whichcertificateshouldbeusedforsigningtheissuedtoken?Althoughasigningcertificatehasalreadybeenidentifiedintheconfigurationclass,GetScopeshouldconfirmthatcertificate(asdonebythetemplateimplementa-tion)oroverrideitwithcustomcriteria—forexample,ifsomethingintherequestinfluenceswhichcertificateshouldbeused.

❑ IstheintendedtokendestinationarecognizedRP?Asdiscussedearlier,normallyanSTSissuestokensonlytotheRPURIsthathavebeenexplicitlyprovisioned.Iftheincomingwtrealm(availableinRequestSecurityTokenviathepropertyAppliesTo)doesnotcorrespondtoaknownRP,anInvalidRequestExceptionshouldbethrown.

Note ThetemplateimplementationofGetScopeperformsthecheckagainstahard-codedlist.OnecouldarguethatavalidationcheckwouldbelongtotheValidateRequestmethod,buttheitemaboutencryptionthatfollowsshowshowGetScopewouldneedtoqueryanRPsettingsdatabaseanyway.

IftheAppliesTovalueisvalid,itisfedintotheScopeobject.ItwillbeneededfortheAudienceRestrictionelementoftheissuedtoken,whichinturnwillbevali-datedbyWIFagainstthe<audienceURI>configelementontheRP.

❑ Shouldtheissuedtokenbeencrypted?Ifyes,withwhichcertificate?TheSTSconfigurationshouldspecifywhetherthetokenshouldbeencrypted.Ifitshould

Page 41: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

110 Part II Windows Identity Foundation for Identity Developers

be,thesamestorethatwasusedforestablishingwhethertheRPwasvalidshouldalsocarryinformationaboutwhichencryptioncertificateshouldbeused.Thetemplateusesavaluefromconfig.

❑ Towhichaddressshouldthetokenbereturned?Thetemplateassumesthatwtrealm—thatis,theAppliesTovalue—isboththeidentifieroftheRPanditsnetwork-addressableURI.Asaresult,GetScopeassignsthevalueofAppliesTototheReplyToAddresspropertyoftheScopeobject.

Important AlthoughinmanycasesitistruethatAppliesTocontainsthenetworkaddressableendpointofoneRP,thatdoesnotalwayshold.Sometimeswtrealmwillbealogicalidentifierfortheapplicationratherthananetworkaddress,andtheactualaddresstowhichthetokenshouldbereturnedwillbedifferent.Awayofhandlingthisisbysendingtheactualaddressintherequestviathewreplyparameter,andthenassigningittoScope.ReplyToAddress(fromRequestSecurityToken.ReplyTo).ReplyToaddressesshouldalwaysbethoroughlyvalidatedbecausesupportingwreplyopensyourSTSuptoredirectattacks.

Note ADFS2.0doesnothandlewreply.

WhentheScopeisready,anumberoflowerleveltoken-issuancepreparationstepstakeplace.Youcaninfluencethoseifyouwantto,butIwon’tgointofurtherdetailshere.Afterthosestepsarecompleted,itisfinallytimetoworkwithclaims.

❑ GetOutputClaimsIdentity ThismethodtakesasinputtheIClaimsPrincipalofthecaller,theRequestSecurityToken,andthe Scope.ItreturnsanIClaimsIdentity,whichcon-tainstheclaimsthatshouldbeissuedinthetokenforthecaller.NotethatatthispointtheIClaimsPrincipalofthecallerisarepresentationoftheIPrincipalobtainedfromtheSTScallerviaFormsauthentication.ThisshouldnotbeconfusedwiththeoutputIClaimsPrincipalcreatedbytheSTS,whichwillbeavailableattheRPaftersuccessfulsign-in.

ThisisperhapstheleastrealisticoftheimplementationsintheSTStemplate.Itreturnstwohard-codedclaims,NameandRole,regardlessofthetargetedRPorthecaller(theonlyconcessionbeingthevalueoftheNameclaim,extractedfromtheincomingprincipal):

protected override IClaimsIdentity GetOutputClaimsIdentity (IClaimsPrincipal principal, RequestSecurityToken request, Scope scope ) { if ( principal == null ) { throw new ArgumentNullException( "principal" ); }

Page 42: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 111

ClaimsIdentity outputIdentity = new ClaimsIdentity(); // Issue custom claims. // TODO: Change the claims below to issue custom claims required by your application. // Update the application's configuration file too to reflect new claims requirement. outputIdentity.Claims.Add( new Claim( System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name ) ); outputIdentity.Claims.Add( new Claim( ClaimTypes.Role, "Manager" ) ); return outputIdentity; }

Inamorerealisticsetting,yourGetOutputClaimsIdentityimplementationwouldneedtomakesomedecisionsabouttheoutgoingIClaimsIdentity.Thesearethequestionsitwillneedtoanswer:

❑ Giventhecurrentrequest,whichclaimtypesshouldbeincluded?ThelistofclaimsthatshouldbeissuedisoftenestablishedperRP,atprovisioningtime.ThatisespeciallycommonforWS-Federationscenarios,andsomeproductswillgoasfarasimplementingthattacticfortheWS-Trustcaseaswell.

Note ADFS2.0usesthatapproachineverycase.ThelistofclaimstoissueisalwaysestablishedonthebasisoftheRPforwhichthetokenisbeingissued.

ChancesarethatthelistofclaimstousewillbeavailableinthesamestoreyouusedinGetScopeforretrievingtheRPURIandencryptioncertificate.

WS-Trust(andWS-Federation,viawreqorwreqptrparameters)supportsrequest-ingaspecificlistofclaimsforeveryrequest.Althoughthatrequiresmorework,whichprobablyincludescheckingonanRP-boundlistiftherequiredclaimsareallowedforthatgivenRP,therearemanyadvantagestotheapproach.Apartfromminimaldisclosureandprivacyconsiderations,possiblyabitoutofscopehere,oneobviousadvantageisthatthiscanhelpkeepthetokensizeundercon-trol.AtokenrepresentingaWindowsidentitycanhavemanygroupclaims.Ifforagiventransactionthegroupclaimisnotrequired,beingabletoexcludeitcandramaticallyshrinktheresultingtoken.

Ifyouwanttosupportrequeststhatspecifytherequiredclaims,you’llfindthatlistintheRequestSecurityToken.Claimscollection.

❑ Giventhecurrentprincipal,whichclaimvaluesshouldbeassigned?Togetherwiththerequestauthenticationmethod,thisisthequestionthatdetermineswhetheryourSTSisanIP-STSoranR-STS.

Page 43: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

112 Part II Windows Identity Foundation for Identity Developers

OneIP-STSusessomeclaimsoftheincomingIClaimsPrincipalforlookingupthecallerinoneormoreattributestores,fromwheretheSTSwillretrievethevaluestoassigntotheestablishedclaimtypes.That’sthedirectdescendentofusingausernameforlookingupattributesinaprofilestore;infact,itcantakeplaceinexactlythesamewayifyouhaveausernameclaim.Ofcourse,youarenotlimitedtoit—youcanuseanyclaimyoulike.

OneR-STSprocessestheclaimsintheincomingIClaimsPrincipalinarbitraryways,storingtheresultsinotherclaimsintheoutgoingIClaimsIdentity.NotethattheSTScanalsojustcopysomeclaimsfromtheincomingtokentotheoutgoingonewithoutmodification,anditcanevenaddnewclaimsinthesamewaytheIP-STSdoes.I’llshowsomeexamplesofthislater,duringthefederationandhome-realmdiscoverydiscussions.

ADFS2.0offersamanagementUI,whereadministratorscanspecifyhowtosourceortransformclaims.ThemappingscanbespecifiedviaasimpleUIorviaaSQL-likelanguagethatisespeciallywellsuitedforclaimsissuance.InyourownSTS,youcanembedthecorrespondingcodedirectlyinGetOutputClaimsIdentity,oryoucandevelopamechanismfordrivingitsbehaviorfromoutside.

MetadataYouknowaboutmetadatafromChapter3.IfyouneedtochangesomethinginthemetadatadocumentofoneRP,youcansimplyeditit.Perhapsthat’snotthegreatestfunyou’llhave,butitisfeasible.

DoingthesameforoneSTSisoutofthequestionbecauseanSTSmetadatadocumentmustalwaysbesigned.TheWIFSDKhasoneexampleshowinghowtousetheWIFAPIforgener-atingametadatadocumentprogrammatically.It’snotrocketscience,justalotofserializa-tion.Generatingthedocumenthastheadvantageofkeepingitautomaticallyupdatedifyouplayyourcardswellandreadthingsfromtheconfig.Italsohasanotheradvantageofgrant-ingyoubettercontrolofcomplicatedsituations,suchascasesinwhichonthesameWebsiteyouexposebothWS-FederationandWS-Trustendpoints.

Anydynamiccontentgenerationmechanismwilldo.MyfavoriteisexposingaWCFserviceandhidingthe.svcextensionwithsomeIISURLrewriting.

SingleSign-on,SingleSign-out,andSessionsInthissection,I’llformalizesomeofthesession-relatedconceptsI’vebeenhintingatsofar.Namely,I’llhelpyouexplorehowWIFcanreducethenumberoftimesauserispromptedforcredentialswhenbrowsingWebsitesthataresomehowrelatedtoeachother.I’llshowyouhowyoucansignoutauserfrommultipleWebsitesatonce,makingsurenodangling

Page 44: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 113

sessionsarestillopen.Finally,I’llshareafewtricksyoucanusefortweakingthewayinwhichWIFhandlessessions.

Single Sign-onInChapter3,IillustratedthedancethatWS-FederationprescribesforsigninginarelyingpartyandhowtheWIFobjectmodelimplementsthat.Let’smovethescenarioalittlefurtherbysupposingthatyouwanttomodelthecaseinwhichtheuservisitsmorethanoneRPapplication.

IftheRPshaveabsolutelynothingincommon,thereisnotmuchtobesaid:everyRPsessionwillhaveitsownindependentstory.Butwhathappensif,forexample,twoRPstrustthesameSTS?Thingsgetmoreinteresting.Figure4-4brieflyrevisitsthesign-insequence,showingtheusersigninginthefirstRPapplication,namedA.

STS

STS A

5

A

3

51

23 4

FIGURE4-4 TheusersignsintheRPnamedA,andinsodoingitreceivessessioncookiesbothfromtheSTSandA

Bynow,youknowthedrill:

1. TheusersendsaGETforapageonA.

2. TheuserisredirectedtotheSTS.

3. TheuserisauthenticatedbywhateversystemtheSTSchoosesandobtainsasessioncookie.

4. Theusergetsbackatoken.

5. TheusersendsthetokentoAandgetsbackasessioncookie.

Herestep3isespeciallyinteresting:InFigure4-4,IassumedtheauthenticationmethodpickedbytheSTSinvolvesthecreationofasessionwiththeSTSsiteitself.That’sareason-ableassumptionbecausethat’spreciselythecasewithcommonauthenticationmethods

Page 45: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

114 Part II Windows Identity Foundation for Identity Developers

suchasKerberos(whichleveragesthesessionthattheusercreatedfromherworkstationatlogintime)orFormsauthentication(whichdropsasessioncookie,justliketheWIFSTStemplatedoes).Ifthatisthecase,attheendofthesign-insequencetheuser’smachinewillhavetwocookies:onerepresentingthesessionwithA,createdbyWIF,andonerepresentingthesessionwiththeSTS.Startingfromthatsituation,let’snowlookatFigure4-5toseewhathappenswhentheusersignsinwithB,anotherRP,thattruststhesameSTS.

STS

B

4 A

1

2

3

4STS A

B

FIGURE4-5 TheusersignsintotheRPnamedB,andtheexistingsessionwiththeSTSallowstheusertosigninwithoutbeingpromptedfortheSTScredentials

Theflowstartsasusual,theuserrequestsapagefromB(step1,asshowninFigure4-5)andgetsredirectedtotheSTStoobtainatoken(step2).However,thistimetheuserisalreadyauthenticatedwiththeSTSsitebecausethereisanactivesessionrepresentedbytheSTScookie.ThismeanstherequestfortheSTSpage—say,Default.aspxifyouareintheWIFSTStemplatecase—leadsstraighttoexecutionoftheSecurityTokenServiceissuingsequencewithoutshowingtotheuseranyUIforcredentialgathering.Thetokenisissuedsilently(step3)andforwardedtoB(step4)accordingtotheusualsequence.FromthemomenttheuserclicksonthelinktoBandthebrowserdisplaystherequestedpagefromB,onlysomeflickeringoftheaddressbarinthebrowserwillgiveawaythefactthatsomeauthenticationtookplaceunderthehood.That’sprettymuchwhatSingleSign-on(SSO)means:theuserwentthroughtheexperienceofsigninginonlyonce,andfromthatmomentonthesystemisabletogainaccesstofurtherRPswithoutpromptingtheuserforcredentialsagain.

SSOisanall-timefavoriteforendusers.UsingasinglesetofcredentialsfordifferentWebsiteswithoutbeingreproachedforit?Typingstuffonlyonce?Countmein!Thisisalsosomethingthatgreatlypleasessystemadministrators,becausereducingthenumberofcredentialstomanageeasestheadministrativeburden,lowerstheprobabilitythatuserswillreusethesamepasswordindifferentWebsites,andsoon.

Page 46: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 115

Note Bynow,youcancertainlyseethefundamentaldifferencebetweenauthenticatingwithanSTSonlyonce,andsilentlyobtainingtokensformultipleWebsitesafterthatsinglecredentialgatheringmomentandreusingthesamecredentialsacrossmultipleWebsites(eachhandlingtheirownauthentication).Whereasthefirstapproachminimizesthechancesofpasswordsbeingstolen,thesecondmaximizesit.

You’llfindthatalthoughmostuninitiatedpeoplewillnotunderstandmostofthestuffIcoveredinthisbook,everybodywillhaveaclear,intuitiveunderstandingandappreciationofSSO.Perhapsnotsurprisingly,SSObecametheHolyGrailoftheindustrylongbeforetheemergenceofclaims-basedidentity,andasoftodayalotofpeoplethinkthattheultimategoalofidentitymanagementshouldbeuniversalSSO.

Thegoodnews?AslongastheSTScreatesasessioninitsauthenticationmethod,havingSSOacrossWebsiteRPsprotectedviaWIFissomethingthatworksrightoutofthebox.There’snoarcaneWS-Federationtrickhere,justgoodoldcookiesandabitoftrustmanagement.

The hands-on lab ASP.NET Membership Provider and Federation (c:\IdentityTrainingKit2010\Labs\MembershipAndFederation) demonstrates how you can easily obtain SSO across Web sites using WIF. In fact, it shows how it is enough to add a page to an existing Web site, without modifying anything else, to add IP capabilities to it. The scenario in the lab modifies a Web site secured via the Membership provider, but this pattern can be applied to any authentication system.

Single Sign-outInoneofthoserareinstancesinwhichbuildingiseasierthandestroying,youareabouttodiscoverthatSingleSign-outissomewhathardertoimplementthanSingleSign-on.

SingleSign-out,orSSOut,takesplacewhentheterminationofonesessionwithaspecificRPtriggersthecleanupofstateandothersessionsacrossthesameübersession.Inotherwords,signingoutfromoneWebsitecascadesthroughalltheWebsitesthatwerepartoftheSSOclubandsignsoutfromthemaswell.

Note ThebasicideaofSSOutisreadilyunderstoodandcanbeeasilyexperiencedevenoutsidefederatedscenarios:thesign-outoptionofLiveID,which(atthetimeofthiswriting)throwsyououtatoncefromalltheWebsitesacceptingLiveIDyou’vebeensigninginto,isagoodexampleofthat.However,inliterature“SingleSign-out”isalmostalwaysusedasasynonymof“federatedsign-out”andisexpectedtobehaveasspecifiedbyWS-FederationorSAMLP.

Page 47: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

116 Part II Windows Identity Foundation for Identity Developers

ThemechanicsofSSOutarenotverystraightforward,especiallybecausetheoutcomeoftheentireprocessreliesonalltheentitiesinvolvedreceivingmessagesandcomplying.Bothofthosethingsarehardtoenforcewithoutreliablemessagingortransactions;hence,theentirethingendsupbeinga“makeyourbesteffort”attempt.ThisstateofaffairswaswellknowntotheauthorsoftheWS-Federationspecification,whowerenotespeciallyprescriptiveindescribingthemessagesandmechanismsusedforimplementingSSOut.WIFdoessupportSSOutoutoftheboxforRPs,buttheSTStemplateisnotespeciallythoroughinimplement-ingallitsdetails.Inthissection,I’llclueyouintothethingsyouneedtoaddforachievingmorecompletesupport.

Signing Out from One RPBeforegettingintothedetailsofhowtohandlesigningoutfrommultipleWebsites,let’sseewhatittakestosignoutfromjustone.

Whatkeepsausersessionalive,apartfromthesheerFormsauthenticationmachinery?Firstofall,it’stheexistence(andvalidity)ofthesessioncookiegeneratedatsign-ontime.ThedefaultnameusedbyWIFforthatcookieisFedAuth,withanadditionalFedAuth1…FedAuthnifthesizeoftheSessionSecurityTokenrequiresmultiplecookies.Youcaneasilytakecareofthatyourself—it’sjustamatterofcallingFormsAuthentication.SignOutanddeletingthesessioncookie(byhandorviaSessionAuthenticationModule.DeleteSessionTokenCookie).

Second,it’sthesessionwiththeSTS.IfyoudeletethesessionwiththeRPbuttheuserstillhasavalidsessionwiththeSTS,shewillstillhaveaccesstotheRP.ThefirstunauthenticatedGETelicitstheusualredirecttotheSTS,andavalidsessionmeansthattheuserwillbeissuedanewtokenwithoutevenbeingpromptedforcredentials.

TheRPcannotdirectlychangetheSTSsession.Infact,itisnotevensupposedtoknowhowthatsession(ifany)isimplementedtobeginwith!Luckily,WS-FederationdefinesawayfortheRPtoasktheSTStosignoutthecurrentprincipal.ItwillbeuptotheSTStodecidewhatspecificstepsthatentailsinthecontextofitsownimplementation.

ThemechanismthatWS-Federationusesforsigningoutisstraightforward:youaresupposedtodoaGEToftheSTSendpointpagewiththeparameterwa=wsignout1.0andawreplyin-dicatingwhereyouwantthebrowsertoberedirectedafterthesignoutisdone.Onceagain,thisissomethingyoucoulddoyourself;butwhybother,whenthereissomethingthatcantakecareofboththeRPsessioncleanupandsendingthesign-outmessagetotheSTS?ThatsomethingisFederatedPassiveSignInStatus,anASP.NETcontrolthatcomeswithWIF.

FederatedPassiveSignInStatus,asthenameimplies,canbeusedforeasilydisplayingonyourWebsitethecurrentstateofthesession.Dragitonanypage,anditsappearancewillchangeaccordingtowhetheryouhaveavalidsessioninplace.Ifyoudo,bydefaultthecontrolappearsasahyperlinkwiththetext“SignOut.”ClickingthatlinkresultsinthecurrentRPsessionbeingcleanedup.IfthecontrolpropertySignOutActionissettoFederatedSignOut,

Page 48: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 117

thecontroltakescareofsendingthewsignout1.0messagetotheSTSindicatedintheSessionSecurityToken.Handy,isn’tit?That’smyfavoritewayofimplementingsignoutwithWIF—it’seasyandpainless.

Warning FederatedPassiveSignInStatushasaproperty,SignOutPageUrl,thatindicatesthepagethebrowsershouldreturntoafterthesign-outisdone.Inpractice,it’sthewreplyinthewsignout1.0message.Ifyouleavethepropertyblank,WIFsetswreplytoyourwtrealmandappends“login.aspx”toit.ChancesarethatyourWebsitedoesnotcontainaloginpagebe-causeyouareusinganSTS.Ifthat’sthecase,youmightgetanerroratthenextsuccessfulau-thentication.Thebottomlineisthis:makesureyouaddameaningfulvaluetoSignOutPageUrl.

TheWIFSTSTemplateandwsignout1.0InthedescriptionoftheWIFSTStemplate,Ipurposefullyomittedthecodethattakescareofsigningout.NowthatyouknowwhatanSTSissupposedtodoinresponsetoawsignout1.0message,Icangetbacktoitandcompletethedescriptionofthetemplate.Thefollowingcodeshowsthemissingbranch:

else if ( action == WSFederationConstants.Actions.SignOut ) { // Process signout request. SignOutRequestMessage requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri( Request.Url ); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest( requestMessage, User, requestMessage.Reply, Response ); }

SignOutRequestMessageisanalogoustoSignInRequestMessage,inthatit’sjustadictionaryofquerystringvalues.FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequestisnotallthatglamorouseither,I’mafraid.ItjustsignsoutfromtheFormauthenticationsession,deletestheWIFsessiontoken(ifthereisany—theSTStemplatedoesnotincludeSessionAuthenticationManagerbydefault)andredirectstotheaddressindicatedbywreply.

Signing Out from Multiple RPsFromtheperspectiveoftheRPfromwhichtheuserissigningout,cleaningupitsownses-sionandsendingwsignout1.0totheSTSisallthatisneededforclosingthegames.IfthereareotherRPswithwhichtheuserstillentertainsanactivesession,itisresponsibilityoftheSTStopropagatethesign-outtothemaswell.

AllthatislefttodoisfortheotherRPstogetridoftheirsessions.NotethattheSTSalreadyeliminateditsownsessionwiththeuser;hence,thereisnoriskofsilentre-issuingaftertheotherRPsdotheircleanup.

Page 49: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

118 Part II Windows Identity Foundation for Identity Developers

Onceagain,WS-Federationprovidesamechanismforthat.Iwon’tgointothedetailshere—itsufficestosaythatonewayofrequestingacleanuptooneRPissimplybydoingaGETrequestontheRPandincludinginthequerystringtheactionwa=wsignoutcleanup1.0.Youcouldspecifyanaddressviawreplytoreturntoafterthecleanupisdone,butthingscangetproblematichere.WhatifyouhavethreeRPsthatneedtocleanuptheirsessions?IfyouarerelyingonthebrowsertoperformthenecessaryGETs,you’dhavetochaintherequests.Inadditiontobeingcomplicated,thisisaverybrittleapproachbecausesome-thinggoingwrongwithoneRPwouldjeopardizethechanceofsendingcleanuprequeststoallthesubsequentRPsinthelist.TheSTScanavoidusingthebrowserandsendtheGETrequestsdirectly,butagain,thisisnotverystraightforward.Forthosereasonsandothers,thepresenceofawreplyisoptionalinwsignoutcleanup1.0 messages;itisacceptabletore-turnsomethingfromtheRPthatsomehowindicatestheoutcomeoftheoperation.There’smore:thecleanupoperationisrequiredtobeidempotent—thatis,youshouldbeabletocallthesameoperationmultipletimeswithoutaffectingtheoutcomeorraisingerrors.Thisal-lowsyoutoretrytheoperationifyouthinksomethingwentwrong,withoutworryingaboutcreatingerrorsituations.

Nowforsomegoodnews:RPssecuredviaWIFhandlewsignoutcleanup1.0 messagesoutofthebox.TheWSFAMlooksoutforthosemessagesinitsAuthenticateRequesthandler.Iftheincomingmessagehasawsignoutcleanup1.0action,WSFAMpromptlydeletesthesessioncookieanddropsthecorrespondingtokenfromthecache.

WhatsetsapartthecleanupfromallotheractionsI’vedescribedsofaristhatitmightnotendwitharedirect.Ifthemessagecontainsawreply,WSFAMdutifullyreturnsa302messagetotheindicatedlocation;ifitdoesn’t,itwillreturnanimageor.gifofagreencheckmark.

Returningthebitsofoneimageuponsuccessfulcleanupispartofacleverstrategyforworkingaroundthe“chainingofsign-outredirects”problemdescribedearlier.AftertheSTSsuccessfullyclearsitsownsession,itcanreturnapagecontainingan<img>elementforeachRPwhosesessionisupforcleanup.Ifthesrcvalueofthe<img>elementsisoftheformhttps://RPAddress/Default.aspx?wa=wsignoutcleanup1.0,justrenderingthelistofimagesinthebrowsersendsasmanycleanupmessagestotheRPsinthelist.Everysuccessfulcleanupsendsbacktheimageofthegreencheckbox,whichtheSTSpagecanuseforconfirmingthatthesign-outactuallytookplaceforagivenRP.Failuretorendertheimagemightbeanindicationthatsomethingwentwrongwiththecleanupoperations.

AlloftheprecedingactivityreliesonthefactthattheSTSwillkeeptrackoftheRPsforwhichitissuedatokeninthecontextofonefederatedsession.Atsign-outtime,theSTSneedstoremembertheaddressofallRPsinordertogeneratethecorrectcleanupURIsforthesrcoftheimagescollectioninthesign-outpage.TheSTScanusewhateverstate-preservingmech-anismitsownerseesfit.Inmysamples,IusuallykeepthelistofRPURIsinaprotectedcookiebecauseitrequireszerostate-managementcodeontheserver.

Page 50: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 119

DidyougetlostinallthebackandforthrequiredbytheSSOutprocess?Let’stakealookatoneexample.Figure4-6illustratestheSingleSign-outmessageflowacrosstwoWebsitesandacommonSTS,togetherwithwhathappenstotheclient’scookiecollectionasthesequenceprogresses.

WebSiteA WebSiteB STSST

SASP

XAU

TH

SsoS

essio

ns

STSA

SPXA

UTH

SsoS

essio

ns

STSA

SPXA

UTH

SsoS

essio

ns

STS

STS

WebSiteABrowser

POST /WebSiteA/ HTTP/1.1..Cookie: FedAuth__EVENTTARGET=ctl00%24FederatedPassiveSignInStatus1%24signoutLink&…

HTTP/1.1 302 FoundLocation: https://STS/?wa=wsignout1.0&wreply=https%3a%2f%2fWebSiteA%2fDefault.aspx...Set-Cookie: FedAuth=; expires=Fri, 18-Jun-201005:47:03 GMT; path=/SSOWebSiteA/

GET /STS/?wa=wsignout1.0&wreply=https%3a%2f%2fWebSiteA%2fDefault.aspx HTTP/1.1..Cookie: .STSASPXAUTH … SsoSessions

HTTP/1.1 200 OK…Set-Cookie: .STSASPXAUTH=; expires=…; path=/; HttpOnlySet-Cookie: SsoSessions=; expires=… path=/<html>...<body><form method="POST" action=" /?wa=wsignout1.0&wreply=…">You are now signed out of the following sites: <div id="SignoutLinks"> <p><a href='https://WebSiteA/'>WebSiteA/</a> <img src='https://WebSiteA/?wa=wsignoutcleanup1.0'/> </p> <p><a href='https://WebSiteB/'>WebSiteB/</a> <img src='https://WebSiteB/?wa=wsignoutcleanup1.0/></p> </div></form></body>..</html>

GET / WebSiteB/?wa=wsignoutcleanup1.0 HTTP/1.1Cookie: FedAuth=…

1

2

3

4

5

6

WebSiteB

GET / WebSiteA/?wa=wsignoutcleanup1.0 HTTP/1.1

HTTP/1.1 200 OKContent-Type: image/gif...GIF89a

HTTP/1.1 200 OKContent-Type: image/gifSet-Cookie: FedAuth=; expires=…;path=/SSOWebSiteB/...GIF89a

WebSiteA WebSiteB STS

WebSiteA WebSiteB STS

STSA

SPXA

UTH

SsoS

essio

ns

WebSiteA WebSiteB STS

WebSiteA WebSiteB STS

FedA

uth

FedA

uth

FedA

uth

STSA

SPXA

UTH

SsoS

essio

ns

FedA

uth

FIGURE4-6 ASingleSign-outprocesstakingplaceasdescribedinWS-Federation

Page 51: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

120 Part II Windows Identity Foundation for Identity Developers

Let’sexamineeverystep.Inthebeginning,theuserissignedintoWebSiteAandWebSiteBviatokensobtainedfromSTS,andhisbrowseriscurrentlyonWebSiteA.Hiscookiecollec-tioncontainsaFedAuthsessioncookieforeachRPandoneFormsauthenticationcookie(STSASPXAUTH)withSTS.ItalsohasanSsoSessionscookiewithSTS,whichcontainsthelistofRPsforwhichtheSTSissuedatokeninthecontextofitsSTSASPXAUTHsession.Here’showtheprocessunfolds:

1. TheuserclicksonaFederatedSignInStatuscontrolinstanceonWebSiteA,triggeringaPOSTintheauthenticatedsessiondescribedbyWebSiteA’sFedAuthcookie.TheSignOutActionpropertyofthecontrolissettoFederatedPassiveSignOut.

2. WebSiteAreceivestherequestforsigningout.Asaresult,itdestroysitsownsession(bycleaningFedAuthfromtheWebSiteAcookiecollectionontheclient)andredirectsthebrowsertosendasign-outmessagetotheSTSthatoriginatedthecurrentsession.

3. Thebrowserfollowstheredirect,sendingtotheSTSthesign-outmessage,alongwiththesessioncookieSTSASPXAUTHandthecookiecontainingthelistofRPswithwhomtheusermightstillentertainactivesessions.

4. TheSTSreactsbycleaningupallitscookiesandsendsbackapagethatcontainsimageswhosesrcURIsareinfactcleanupmessagesforalltheRPslistedintheSsoSessionscookie—thatis,WebSiteAandWebSiteB.

5. Thebrowserrendersthefirstimage,pointingtoWebSiteA.Hence,itsendsaGETforitssource,whichinfactdeliversacleanupmessage.WebSiteAalreadycleanedupitssessionbecauseitwastheoriginatoroftheSingleSign-outsequence.IftheSTShadknownthis,itcouldhaveavoidedaddingWebSiteAtothelistofcleanupRPs;however,nothingbadhappens,thankstotheidempotencyrequirementsofwssignoutcleanup1.0messages.WebSiteAsimplyreturnsthebitsoftheGIFindicatingthatcleanupsuccess-fullytookplace.

6. Thebrowserrenderstheimage,pointingtoWebSiteB.WebSiteBreceivesthecleanupmessageandreactsbydeletingitsownFedAuthcookieandreturningthebitsoftheGIFofthecheckmarkasexpected.Atthispoint,allthesessionshavebeencleanedup:theSingleSign-outconcludedsuccessfully,andtheusercanseeontheSTSpagethelistofWebsiteshehasbeensignedoutfrom.

Onceyougetthehangofit,it’sreallynotthathard.OneofthethingsIlikebestaboutthisapproachisthatitallowsyoutoherdthebehaviorofmultipleWebsiteswithoutknowinganydetail.Somesitescouldbehostedonyourintranet,otherscouldbehostedinthecloud,orsitescouldberunningondifferentstacksandoperatingsystems,butaslongastheyallspeakviaWS-Federationandshareacommon,trustedground,therightthingjusthappens.

Page 52: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 121

TheWIFSTSTemplateandSingleSign-outAsyousawearlier,theSTStemplatehandleswssignout1.0messages.However,itdoesnotpropagatethemviawssignoutcleanup1.0totheotherRPsinthesession,nordoesitcontainanymechanismforkeepingtrackoftheRPsinthecurrentsessionatissuancetime.ThesamplediscussedhereofferssuchamechanismintheSingleSignOnManagerclass.ItisafaçadeforacollectionofRPURIssavedinacookie,whichgetsupdatedwiththeRPaddresseverytimetheSTSissuesatoken(inGetOutputClaimsIdentity)andthatcanbelookedupwhenit’stimetosendcleanupmessages.Thatisjustoneexample—youcanuseanyequivalentmechanism.Onceyouhavethatcapability,enhancingtheSTStemplatecodetosupportSSOutiseasy.Considerthefollowingmodifiedversionofthesign-outbranchintheDefault.asp.cs code:

else if ( action == WSFederationConstants.Actions.SignOut ) { // Process signout request. SignOutRequestMessage requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri( Request.Url ); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest( requestMessage, User, /*requestMessage.Reply*/ null, Response ); // new string[] signedInUrls = SingleSignOnManager.SignOut(); lblSignoutText.Visible = true; foreach (string url in signedInUrls) { SignoutLinks.Controls.Add( new LiteralControl(String.Format( "<p><a href='{0}'>{0}</a>&nbsp;<img src='{0}?wa=wsignoutcleanup1.0' title='Signout request: {0}?wa=wsignoutcleanup1.0'/></p>," url))); } }

Thechangesarestraightforward.ThecalltoProcessSignOutRequestdoesnotredirecttowreply,becauseafteritcleanedupitsownsessionthere’sstillworktodothatwouldnotbedoneifitredirectedasinthedefaultcase.Aftercleaningitsownsession,theSTSpreparestheUIforthesign-outbyturningonthevisibilityofasign-outmessage(here,inalabel).ThecalltoSingleSignOutManagerreturnsthelistofalltheRPswhosesessionshouldbecleanedup.Theforeachthatappearsbelowthatusesthatlistforgeneratingandappendingtothepageasmanyimagesasneeded,whichwilldispatchthecleanupmessageoncetheyarerendered.

Page 53: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

122 Part II Windows Identity Foundation for Identity Developers

More About SessionsIbrieflytouchedonthetopicofsessionsattheendofChapter3,whereIshowedyouhowyoucankeepthesizeofthesessioncookieindependentfromthedimensionofitsoriginat-ingtokenbysavingareferencetosessionstatestoredontheserverside.TheWIFprogram-mingmodelgoeswellbeyondthat,grantingyoucompletecontroloverhowsessionsarehandled.HereI’dliketoexplorewithyoutwonotableexamplesofthatprincipleinaction:slidingsessionsandnetworkload-balancer-friendlysessions.

Sliding SessionsBydefault,WIFcreatesSessionSecurityTokenswhosevalidityisbasedonthevalidityoftheincomingtoken.Youcanoverrulethatbehaviorwithoutwritinganycode,byaddingtothe<microsoft.identityModel>elementintheweb.configfilesomethinglikethefollowing:

<securityTokenHandlers> <add type="Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <sessionTokenRequirement lifetime="0:02" /> </add> </securityTokenHandlers>

Note Thelifetimepropertycanrestrictonlythevalidityexpressedbythetokentobeginwith.Intheprecedingcodesnippet,Isetthelifetimeto2minutes,butiftheincomingsecuritytokenwasvalidforjust1minute,thesessiontokenwouldhave1minuteofvalidity.Ifyouwanttoincreasethevaliditybeyondwhattheinitialtokenspecified,youneedtodosoincode(bysubclassingSessionSecurityTokenHandlerorbyhandlingSessionSecurityTokenReceived).

Now,let’ssaythatyouwanttoimplementamoresophisticatedbehavior.Forexample,youwanttokeepthesessionaliveindefinitelyaslongastheuserisactivelyworkingwiththepages.However,youwanttoterminatethesessionifyoudonotdetectuseractivityinthepast2minutes,regardlessofthefactthattheinitialtokenwouldstillbevalid.ThisisacommonrequirementforWebsitesthatrevealpersonallyidentifiableinformation(PII)orgivecontroltobankingoperations.Thosearecasesinwhichyouwanttoensurethattheuserisactuallyinfrontofthemachineandthepagesarenotabandonedtothemercy(ormercenaryinstincts)ofbystanders.

InChapter3,Ihintedatthisscenario,suggestingthatitcouldbesolvedbysubclassingtheSessionAuthenticationModule.Thatistherightstrategyifyouexpecttoreusethisfunction-alityoverandoveragainacrossmultipleapplications,giventhatitneatlypackagesitinaclassyoucanincludeinyourcodebase.Infact,SharePoint2010offersslidingsessionsandimplementsthosepreciselyinthatway.If,instead,thisisanimprovementyouneedtoapply

Page 54: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 123

onlyoccasionally,oryouownjustoneapplication,youcanobtainthesameeffectsimplybyhandlingtheSessionSecurityTokenReceivedevent.Takealookatthefollowingcode:

<%@ Application Language=”C#” %> <%@ Import Namespace=”Microsoft.IdentityModel.Web” %> <%@ Import Namespace=”Microsoft.IdentityModel.Tokens” %> <script runat=”server”> void SessionAuthenticationModule_SessionSecurityTokenReceived (object sender, SessionSecurityTokenReceivedEventArgs e) { DateTime now = DateTime.UtcNow; DateTime validFrom = e.SessionToken.ValidFrom; DateTime validTo = e.SessionToken.ValidTo; double halfSpan = (validTo – validFrom).TotalMinutes / 2; if ( validFrom.AddMinutes( halfSpan ) < now && now < validTo ) { SessionAuthenticationModule sam = sender as SessionAuthenticationModule; e.SessionToken = sam.CreateSessionSecurityToken(e.SessionToken.ClaimsPrincipal, e.SessionToken.Context, now, now.AddMinutes(2), e.SessionToken.IsPersistent); e.ReissueCookie = true; } } //...

Asyoucertainlyguessed,thisisafragmentoftheglobal.asaxfileoftheRPapplication.SessionSecurityTokenReceivedgetscalledassoonasthesessioncookieisdeserialized(orresolvedfromthecacheifyouareinsessionmode).Hereyouverifywhetheryouarewithinthesecondhalfofthevaliditywindowofthesessiontoken.Ifyouare,youextendthevaliditytoanother2minutes,startingnow.Thatchangetakesplaceonthein-memoryinstanceoftheSessionSecurityToken.SettingReissueTokentotrueinstructstheSessionAuthenticationModuletopersistthenewsettingsinthecookieaftertheexecutionleavesSessionSecurityTokenReceived.Let’ssaythatthetokenisvalidbetween10:00a.m.and10:02a.m.Ifthecurrenttimefallsbetween10:01a.m.and10:02a.m.—say,10:01:15—thecodesetsthenewvalidityboundariestogofrom10:01:15to10:03:15andsavesthoseinthesessioncookie.

Note ThisisthesameheuristicthatFormsAuthenticationusesforslidingexpiration.Whyrenewthesessiononlyduringthesecondhalfofthevalidityinterval?Well,writingthecookieisnotforfree.Thisisjustaheuristicforreducingthetimesatwhichthesessiongetsrefreshed,butyoucancertainlychoosetoapplydifferentstrategies.

Ifthecurrenttimeisoutsidethevalidityinterval,thisimplementationofSessionSecurityTokenReceivedwillhavenoeffect.TheSessionAuthenticationModulewilltakecareofhandlingtheexpiredsessionrightafter.Notethatanexpiredsessiondoesnotelicitanyexplicitsign-outprocess.IfyourecallthediscussionaboutSSOandSSOutjustafew

Page 55: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

124 Part II Windows Identity Foundation for Identity Developers

pagesearlier,you’llrealizethatiftheSTSsessionoutlivestheRPsessiontheuserwilljustsilentlyre-obtaintheauthenticationtokenandrenewthesessionwithoutevenrealizinganythinghappened.

Sessions and Network Load BalancersBydefault,sessioncookieswrittenbyWIFareprotectedviaDPAPI,takingadvantageoftheRP’smachinekey.Suchcookiesarecompletelyopaquetotheclientandanybodyelsewhodoesnothaveaccesstothatspecificmachinekey.

Thisworkswellwhenalltherequestsinthecontextofausersessionareaimedatthesamemachine.ButwhathappenswhentheRPishostedonmultiplemachines—forexample,inaload-balancedenvironment?Asessioncookiemightbecreatedononemachineandsenttoadifferentmachineatthenextpostback.UnlessthetwomachinessharethesamemachinekeyanduseitforencryptingthecookieinsteadoftakingadvantageoftheDPAPIEncryptionkey,acookieoriginatedfrommachineAwillbeunreadablefrommachineB.

Therearevarioussolutionstothesituation.Oneobviousoneisusingstickysessions—thatis,guaranteeingthatasessionbeginningwithmachineAkeepsreferringtoAforallsubsequentrequests.Iamnotabigfanofthatsolutionbecauseitdampenstheadvantagesofusingaload-balancedenvironment.Furthermore,youmightnotalwayshaveasayinthematter—forexample,ifyouarehostingyourapplicationsonathird-partyinfrastructure(suchasWindowsAzure),yourcontroloftheenvironmentwillbelimited.

Anothersolutionistosynchronizethemachinekeysofeverymachineandusethoseforencryptingcookies.Ilikethisbetterthanusingstickysessions,butthereisanapproachIlikeevenbetter.Moreoftenthannot,yourRPapplicationwilluseSecureSocketsLayer(SSL),whichmeansyouneedtomakethecertificateandcorrespondingprivatekeyavailableoneverynode.Itmakesperfectsensetousethesamecryptographicmaterialforsecuringthecookieinaload-balancer-friendlyway.

WIFmakestheprocessofapplyingtheaforementionedstrategyinASP.NETapplicationstrivial.Thefollowingcodeillustrateshowitcanbedone:

public class Global : System.Web.HttpApplication { //... void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e) { // // Use the <serviceCertificate> to protect the cookies that are // sent to the client. // List<CookieTransform> sessionTransforms = new List<CookieTransform>(new CookieTransform[] { new DeflateCookieTransform(),

Page 56: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 125

new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate), new RsaSignatureCookieTransform(e.ServiceConfiguration.ServiceCertificate) }); SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly()); e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler); } protected void Application_Start(object sender, EventArgs e) { FederatedAuthentication.ServiceConfigurationCreated += OnServiceConfigurationCreated; }

Insteadofusingtheusualinlineapproach,thistimeIamshowingyouthecode-behindfileglobal.asax.cs.OnServiceConfigurationCreatedis—Surprise!Surprise!—ahandlerfortheServiceConfigurationCreatedeventandfiresjustafterWIFreadstheconfiguration.Ifyoumakechangeshere,youhavetheguaranteethattheywillalreadybeappliedfromtherequestcomingin.

Note Contrarytowhatvarioussamplesouttherewouldleadyoutobelieve,OnServiceConfigurationCreatedisprettymuchtheonlyWIFeventhandlerthatshouldbeassociatedtoitseventinApplication_Start.Thishastodowiththeway(andthenumberoftimes)ASP.NETinvokesthehandlersthoughtheapplicationlifetime.

Thecodeisself-explanatory.ItcreatesanewlistofCookieTransformtransformations,whichtakescareofcookiecompression,encryption,andsignature.ThelasttwotakeadvantageoftheRsaxxxxCookieTransform,takingininputthecertificatedefinedfortheRPintheweb.configfile.

Note Whydoyousignthecookie?Wouldn’titbeenoughtoencryptit?IfyouusetheRPcertificate,encryptionwouldnotbeenough.Remember,theRPcertificateisapublickey.Ifyoujustencryptit,acraftyclientcanjustdiscardthesessioncookie,createanewonewithsuper-privilegesintheclaims,andencryptitwiththeRPcertificate.TheRPwouldnotbeabletotellthedifference.Addingthesignaturesuccessfullypreventsthisattackbecauseitrequiresaprivatekey,whichisnotavailabletotheclientoranybodyelsebuttheRPitself.

ThenewtransformationslistisassignedtoanewSessionSecurityTokenHandlerinstance,whichisthenusedforoverridingtheexistingsessionhandler.Fromthispointon,allsessioncookieswillbehandledusingthenewstrategy.That’sit!AslongasyouremembertoaddanentryfortheservicecertificateintheRPconfiguration,you’vegotnetworkloadbalancing(NLB)–friendlysessionswithouthavingtoresorttocompromisessuchasstickysessions.

Page 57: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

126 Part II Windows Identity Foundation for Identity Developers

FederationAtthebeginningofthechapter,IintroducedtheFederationProvideranddiscussedsomeoftheadvantagesthattheIP-FP-RPpatternoffers.Thetemptationtoexpandthearchitec-turalconsiderationsaboutthisimportantpatternisstrong;however,hereIwanttokeepthefocusonWIFandgiveyouaconcretecodingexample.Therearemanygoodhigh-levelintroductionstothetopicyoucanreferto.

For a good introduction to the subject, refer to AGuidetoClaims-BasedIdentityandAccessControlby Dominick Baier, Vittorio Bertocci, Keith Brown, Matias Woloski, and Eugenio Pace (Microsoft Press, 2010).

WIFdoesnotreallycareiftheSTSusedbytheRPisanIP-STSoranR-STS.Bothtypeslookthesameintheirmetadatadescriptionand,despitethedifferencesinthesequencethatultimatelyleadtothat,theybothissueatokenasrequested.Ithelpstoseethisinactioninaconcreteexample.

Note Asusual,inarealisticscenarioyoucanexpecttheR-STStobeprovidedbyoneADFS2.0instanceplayingtheFProle.Onceagain,foreducationalpurposes,I’lltakeadvantageofcustomSTSeshere.

DoyourecallthefirstexampleweexploredinChapter2?ItwasaclassicRP-IPscenario,butitisveryeasytotransformitintoatoyfederationsample.Justright-clickontheBasicWebSite_STSprojectinSolutionExplorer,selecttheAddSTSReferenceentry,andusethewizardforcreatingyetanothernewSTSprojectinthecurrentsolution.

Note TheAddSTSReferenceWizardaddsan<httpModules>elementinthe<system.web>sectionofBasicWebSite_STSconfig,whichdoesnotplaywellwiththeIISintegratedpipeline.Youmighthavetocommentoutthat<httpModules>entry.

Figure4-7showsthenewsolutionlayout.

Page 58: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 127

FIGURE4-7 BasicWebSitetrustsBasicWebSite_STS,whichinturntrustsBasicWebSite_STS_STS

NothingchangedfortheRP,BasicWebSite,whichisstilloutsourcingauthenticationtoBasicWebSite_STS.BasicWebSite_STSwasanIP-STSwhenwestarted,becauseitwasanunmodifiedinstanceoftheWIFSTStemplate.AfterthewizardconfiguredittooutsourceauthenticationtoBasicWebSite_STS_STS,however,BasicWebSite_STSbecameanR-STS;therefore,itslogin.aspxpagewillnotbeusedanymore.Ifyourunthesolutionyou’llobservethebrowserbeingredirectedfromBasicWebSitetoBasicWebSite_STS,whichwillredirectrightawaytoBasicWebSite_STS_STS,whichwillfinallyshowitsownlogin.aspxpage.AfteryouclickSubmitontheloginform,theflowwillgothroughthechainintheoppositeorder:BasicWebSite_STS_STSwillissueatokenthatwillbeusedforsigninginBasicWebSite_STS,whichinturnwillissueanewtokenthatwillbeusedforsigninginBasicWebSite. Figure4-8summarizesthesign-inflow.

Page 59: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

128 Part II Windows Identity Foundation for Identity Developers

Browser

BasicWebSite_STS_STS

BasicWebSite1

23 46

7

Trust

Trust

BasicWebSite_STS

5A

5

FIGURE4-8 TheauthenticationflowlinkingBasicWebSite,BasicWebSite _STS,andBasicWebSite_STS_STS

1 TheuserrequestsapagefromBasicWebSite.

2 Becausetheuserisnotauthenticated,heisredirectedtoBasicWebSite_STSforauthentication.

3 BasicWebSite_STSitselfoutsourcesauthenticationtoBasicWebSite_STS_STS;hence,itredirectstherequestaccordingly

4 OncetheusersuccessfullyauthenticateswithBasicWebSite_STS_STS,hegetsbackatoken.

5 TheusergetsredirectedbacktoBasicWebSite_STS,whichvalidatesthetokenfromBasicWebSite_STS_STSandconsiderstheuserauthenticatedthankstoit.

6 BasicWebSite_STSissuesatokentotheuser,asrequested.

7 TheusergetsbacktoBasicWebSitewiththetokenobtainedfromBasicWebSite_STSasrequired,andtheauthenticatedsessionstarts.

Convoluted?Abit,perhaps.Ontheupside,BasicWebSiteisnowcompletelyisolatedfromtheactualidentityprovider—changesintheIPwillnotaffecttheRP.IfyouhavemultipleRPs,youcannowhavethemalltrustthesameR-STS,whichwilltakecareofenforcinganychangesintherelationshipwiththeIP(orIPs,asI’llshowinamoment)withoutrequiringanyad-hocinterventionontheRPcodeorconfigurationitself.Prettyhandy!

Page 60: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 129

Transforming ClaimsTheexampleintheprecedingsectionmodifiedtheauthenticationflowtoconformtothefederationpattern,butitdidn’treallychangethewayinwhichBasicWebSite_STSprocessesclaims.Withitshard-codedclaimsentries,thedefaultWIFSTStemplatebehaviormimicsthatofanIP-STS;whereasinitsnewFProle,BasicWebSite_STSisexpectedtoprocesstheincom-ingclaims(inthiscase,fromBasicWebSite_STS_STS).IfyouwanttochangeBasicWebSite_STSintoaproperR-STS,youneedtomodifytheGetOutputClaimsIdentity methodoftheCustomSecurityTokenServiceclass.

Asyoualreadyknow,inGetOutputClaimsIdentitytheincomingclaimsareavailableintheIClaimsPrincipal principalparameter.Youcanprettymuchdoanythingyouwantwiththeincomingclaims,butIfinditusefultoclassifythepossibleactionsintothree(non-exhaustive)categories:pass-through,modification,andinjectionofnewclaims.Theyarerepresentedinstep5aofFigure4-8.HereisasimpleexampleofaGetOutputClaimsIdentityimplementationthatfeaturesallthreemethods:

protected override IClaimsIdentity GetOutputClaimsIdentity (IClaimsPrincipal principal, RequestSecurityToken request, Scope scope ) { if ( null == principal ) { throw new ArgumentNullException( "principal" ); } ClaimsIdentity outputIdentity = new ClaimsIdentity(); IClaimsIdentity incomingIdentity = (IClaimsIdentity)principal.Identity; // Pass-through Claim nname = (from c in incomingIdentity.Claims where c.ClaimType == ClaimTypes.Name select c).Single(); Claim nnnm = new Claim(ClaimTypes.Name, nname.Value, ClaimValueTypes.String, nname.OriginalIssuer); outputIdentity.Claims.Add(nnnm); // Modified string rrole = (from c in incomingIdentity.Claims where c.ClaimType == ClaimTypes.Role select c.Value).Single(); outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, "Transformed " + rrole)); // New outputIdentity.Claims.Add(new Claim("http://maseghepensu.it/hairlength", "a value", ClaimValueTypes.Double)); return outputIdentity; }

Page 61: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

130 Part II Windows Identity Foundation for Identity Developers

Beforegoingintothedetailsofhowthevarioustransformationswork,itisfinallytimetotakeadeeperlookatthatClaimclasswe’vebeenusingwithoutgivingittoomuchthoughtsofar.Herearethevariouspropertiesoftheclassandsomemethodsofinterest:

public class Claim { // Methods public virtual Claim Copy(); public virtual void SetSubject(IClaimsIdentity subject); // Properties public virtual string ClaimType { get; } public virtual string Issuer { get; } public virtual string OriginalIssuer { get; } public virtual IDictionary<string, string> Properties { get; } public virtual IClaimsIdentity Subject { get; } public virtual string Value { get; } public virtual string ValueType { get; } }

OnethingthatimmediatelygrabsyourattentionisthatallpropertiesofClaimareread-only:aftertheclasshasbeencreated,thevaluescannotbechanged.TheonlyexceptionisthesubjecttowhichtheClaiminstanceisreferringto:SetSubjectwillchangethevalueoftheSubjectpropertytoanewIClaimsIdentity.

YouarealreadyfamiliarwithValueandClaimTypebecauseI’vebeenusingthosethroughouttheentirebook.ValueTypeismoreinteresting.Itallowsyoutospecifyatypefortheclaimvalue,whichtheclaimconsumercanusetodeserializetheclaiminacommonlanguageruntime(CLR)type(orwhatevertypesystemyourprogrammingstackrequiresifyouarenotin.NET)otherthanthedefaultstring.Thatisakeyenablerforapplyingcomplexlogictoclaims.WithoutknowingthatDateOfBirthshouldbedeserializedinaDateTime,you’llfinditdifficulttoverifywhetheritisbeloworaboveagiventhreshold.NotethattheValueTypeisjustoneindication:theValuereturnedbytheclaimisalwaysastringregardlessoftheValueType.You’llhavetocalltheappropriateParsemethod(orsimilar)yourself.

ThePropertiesdictionaryisusedforcarryingextrainformationabouttheclaimitselfwhentheprotocolrequiresit.Forexample,inSAML2youmighthavepropertiessuchasSamlAttributeDisplayNameassignedtoaclaim.

Note TheWIFtokenhandlerswillnotserializetheproperties.Ifyouwantthemtotravel,you’llhavetotakecareofthatyourself.

TheIssuerpropertyisastringrepresentingthetokenissuerfromwhichtheclaimhasbeenextracted.ThestringitselfcomesfromthemappingthatIssuerNameRegistrymakesbetweenthecertificateusedforsigningthetokenandthefriendlynameassignedtotheassociatedissuer.TheOriginalIssuerpropertyrecordsthefirstissuerthatproducedthisclaiminthefed-erationchain.I’veincludedmoredetailsaboutthisinthe“Pass-ThroughClaims”section.

Page 62: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 131

ClaimTypesandValueConstantsWIFofferstwocollectionsofstringconstantsthatgathermostoftheknownclaimtypeURIs.OneisMicrosoft.IdentityModel.Protocols.WSIdentity.WSIdentityConstants.ClaimTypes(whichisalmostthesameastheWCFcollectionSystem.IdentityModel.Claims.ClaimTypes);theotherisMicrosoft.IdentityModel.Claims.ClaimTypes(whichisasupersetofthefirstone).Foryourreference,thecontentofMicrosoft.IdentityModel.Claims.ClaimTypesislistednext.Notethatsomepopularclaimtypes(suchasGroup)arekeptinthePripsubtypeandareoftenoverlooked.PripstandsforWS-FederationPassiveRequestorInteroperabilityProfile,whichisaspecificsubsetofWS-Federationusedduringearlymultivendorinteroperabilitytests.

public static class ClaimTypes { // Fields public const string Actor = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor"; public const string Anonymous = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/anonymous"; public const string Authentication = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authentication"; public const string AuthenticationInstant = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant"; public const string AuthenticationMethod = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod"; public const string AuthorizationDecision = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authorizationdecision"; public const string ClaimType2005Namespace = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims"; public const string ClaimType2009Namespace = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims"; public const string ClaimTypeNamespace = "http://schemas.microsoft.com/ws/2008/06/identity/claims"; public const string CookiePath = "http://schemas.microsoft.com/ws/2008/06/identity/claims/cookiepath"; public const string Country = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country"; public const string DateOfBirth = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth"; public const string DenyOnlyPrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid"; public const string DenyOnlyPrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid"; public const string DenyOnlySid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid"; public const string Dns = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dns"; public const string Dsa = "http://schemas.microsoft.com/ws/2008/06/identity/claims/dsa";

Page 63: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

132 Part II Windows Identity Foundation for Identity Developers

public const string Email = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"; public const string Expiration = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration"; public const string Expired = "http://schemas.microsoft.com/ws/2008/06/identity/claims/expired"; public const string Gender = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender"; public const string GivenName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"; public const string GroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid"; public const string Hash = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/hash"; public const string HomePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/homephone"; public const string IsPersistent = "http://schemas.microsoft.com/ws/2008/06/identity/claims/ispersistent"; public const string Locality = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"; public const string MobilePhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mobilephone"; public const string Name = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; public const string OtherPhone = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/otherphone"; public const string PostalCode = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode"; public const string PPID = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier"; public const string PrimaryGroupSid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid"; public const string PrimarySid = "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid"; public const string Role = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; public const string Rsa = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/rsa"; public const string SerialNumber = "http://schemas.microsoft.com/ws/2008/06/identity/claims/serialnumber"; public const string Sid = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid"; public const string Spn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn"; public const string StateOrProvince = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince"; public const string StreetAddress = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress"; public const string Surname = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname";

Page 64: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 133

public const string System = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/system"; public const string Thumbprint = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint"; public const string Upn = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"; public const string Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/uri"; public const string UserData = "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata"; public const string Version = "http://schemas.microsoft.com/ws/2008/06/identity/claims/version"; public const string Webpage = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/webpage"; public const string WindowsAccountName = "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname"; public const string X500DistinguishedName = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname"; // Nested Types public static class Prip { // Fields public const string ClaimTypeNamespace = "http://schemas.xmlsoap.org/claims"; public const string CommonName = "http://schemas.xmlsoap.org/claims/CommonName"; public const string Email = "http://schemas.xmlsoap.org/claims/EmailAddress"; public const string Group = "http://schemas.xmlsoap.org/claims/Group"; public const string Upn = "http://schemas.xmlsoap.org/claims/UPN"; } }

Youcan,ofcourse,createyourownclaimtypes.However,IsuggestthatbeforedoingsoyoutakealookattheInformationCardFoundationWebsite,which(amongotherthings)gathersalltheknownandemergentclaimtypesfromthecommunity.Thedirectaddressishttp://informationcard.net/resources/claim-catalog.

WIFalsooffersvariousconstantsrepresentingcommontypesofclaimvalues:

public static class ClaimValueTypes { // Fields public const string Base64Binary = "http://www.w3.org/2001/XMLSchema#base64Binary"; public const string Boolean = "http://www.w3.org/2001/XMLSchema#boolean"; public const string Date = "http://www.w3.org/2001/XMLSchema#date"; public const string Datetime = "http://www.w3.org/2001/XMLSchema#dateTime"; public const string DaytimeDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#dayTimeDuration"; public const string Double = "http://www.w3.org/2001/XMLSchema#double"; public const string DsaKeyValue = "http://www.w3.org/2000/09/xmldsig#DSAKeyValue"; public const string HexBinary = "http://www.w3.org/2001/XMLSchema#hexBinary"; public const string Integer = "http://www.w3.org/2001/XMLSchema#integer";

Page 65: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

134 Part II Windows Identity Foundation for Identity Developers

public const string KeyInfo = "http://www.w3.org/2000/09/xmldsig#KeyInfo"; public const string Rfc822Name = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"; public const string RsaKeyValue = "http://www.w3.org/2000/09/xmldsig#RSAKeyValue"; public const string String = "http://www.w3.org/2001/XMLSchema#string"; public const string Time = "http://www.w3.org/2001/XMLSchema#time"; public const string X500Name = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name"; private const string Xacml10Namespace = "urn:oasis:names:tc:xacml:1.0"; private const string XmlSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; private const string XmlSignatureConstantsNamespace = "http://www.w3.org/2000/09/xmldsig#"; private const string XQueryOperatorsNameSpace = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816"; public const string YearMonthDuration = "http://www.w3.org/TR/2002/WD-xquery-operators-20020816#yearMonthDuration"; }

ThetypesarerepresentedaccordingtoW3CandOASIStypeURIs,butthemappingtoCLRtypesisobviousmostofthetime.

NowthatyouunderstandabitbetterhowtheClaimclassworks,let’sresumethediscussionabouttheclaimtransformations.

Pass-Through ClaimsOneofthemostcommontransformationsyou’llwanttoapplytoyourclaimsis…notransformationatall.SometimestheIPdirectlyissuestheclaimstheRPneeds;hence,youhavetomakesurethatthoseclaimsarereissuedas-isbytheR-STS.

Althoughtheclaimtypeandvaluecomestraightfromtheincomingvalues,thefactthatthenewclaimisissuedinatokensignedbytheR-STSmakestheR-STSitselftheassertingpartyandshadowstheoriginalissuer.TheR-STSmightevenbeacceptingtokensfrommultipleissuers,whichwouldcomplicatethingsfurther.Therecouldbesituationsinwhichknow-ingtheactualoriginoftheclaimcouldchangethewayinwhichtheinformationitcarriesisprocessed;therefore,itisimportanttosomehowlettheRPknowwhichIPissuedtheclaiminthefirstplace.ThisisdonebysettingtheOriginalIssuerpropertyoftheoutgoingclaimtotheOriginalIssuercarriedbytheclaimyouarere-issuing.HerearetherelevantlinesfromtheGetOutputClaimsIdentityimplementationshownearlier:

// Pass-through Claim nname = (from c in incomingIdentity.Claims where c.ClaimType == ClaimTypes.Name select c).Single(); Claim nnnm = new Claim(ClaimTypes.Name, nname.Value, ClaimValueTypes.String, "," nname.OriginalIssuer); outputIdentity.Claims.Add(nnnm);

Page 66: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 135

Inthisexample,theclaimtobereissuedistheNameclaim.Thecoderetrievesitfromtheincomingprincipal,andthenitjustcreatesanewclaimthatcopieseverythingfromtheorigi-nalexceptfortheissuer.(HeretheissuerparameterisleftemptybecauseitisgoingtobeoverriddenwiththecurrentR-STS,anyway.)ThatsnippetisdesignedtosurfacetoyoutheuseofOriginalIssuer,butinfactyoucanuseamorecompactformusingCopyasshownhere:

// Pass-through Claim nname = (from c in incomingIdentity.Claims where c.ClaimType == ClaimTypes.Name select c).Single(); Claim nnnm = nname.Copy(); outputIdentity.Claims.Add(nnnm);

Modifying Claims and Injecting New ClaimsThedistinctionbetweenmodifyingclaimsandinjectingnewclaimsisabitphilosophical,becausefromthecodeperspectivethetwotransformationsarethesame.

Modifyingaclaimmeansproducinganewclaimbyprocessingorcombiningthevalueofoneormoreincomingclaims,accordingtoarbitrarylogic.AnexcellentexampleofthatisgivenbytheADFS2.0claims-transformationlanguage,whichallowsadministratorstospecifytransformationswithoutwritinganyexplicitcode.Ofcourse,inGetOutputClaimsIdentityyoucanliterallywritewhateverlogicyouwant.

Injectingnewclaimsusuallyentailslookingupnewinformationabouttheincomingsubject—informationthatwasnotavailabletotheIPbutthattheRPneeds.Aclassicexampleisthebuyer’sprofile:imaginethattheuserisoneemployee,theIPistheuser’semployer,andtheRPissomekindofonlineshop.TheR-STSmightmaintaininformationsuchasthelast10itemstheuserbought,datathattheemployerdoesnotkeeptrackofandthatshouldbeinjectedbytheresourceorganization—forexample,intheR-STS.Thechallengeherecanbechoosingwhichincomingclaimsshouldbeusedforuniquelyidentifyingthecur-rentuserandlookinguphisdataintheR-STSprofilestore.WhereastheIPhasonestrongincentivetohavesuchauniqueidentifier—becausethatisusuallyneededinordertoapplythemechanicsoftheauthenticationmethodofchoice—theR-STSdoesnothaveasimilarrequirementperse.Theclaimschosenshouldbeunique,atleastinthecontextofthecurrentR-STS,andstableenoughtobereusableacrossmultipletransactions.Thee-mailclaimisagoodexample,butofcourseit’snotaperfectonebecausee-mailaddressesdochangefromtimetotime—thinkofthesituationwhereinternsbecomefull-timeemployeesandsimilarevents.

Home Realm DiscoveryOneofthegreatadvantagesoffederationisthepossibilityofhandlingmultipleidentityproviderswithouthavingtochangeanythingintheRPitself.TheFederationProviderscan

Page 67: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

136 Part II Windows Identity Foundation for Identity Developers

takecareofallthetrustrelationships.Extendingtheaudienceoftheapplicationwithoutpay-inganycomplexitypriceisgreat;however,thesheerpossibilityofusingmorethanoneIPdoesintroduceanewproblem:whenanunauthenticatedusershowsup,whichIPshouldsheultimatelyauthenticatewith?Inthetrivialfederationcaseexaminedsofar,theonewithoneFPandoneIP,theanswerisobvious:theredirectchaincrawlsallthewaytotheIPandback.WhenyouhavemorethanoneIP,however,howdoestheR-STSdecideiftheredirectshouldgotoIPAorIPB?

TheproblemofdecidingwhichIPshouldauthenticatetheuseriswellknowninliterature,anditgoesunderthenameofHomeRealmDiscovery(HRD).TheHRDproblemhasmanysolutions,althoughasoftodaytheyaremostlyadhocandwhatworksinonegivenscenariomightnotbesuitableforanother.Forexample,oneclassicsolution(offeredoutoftheboxbyADFS2.0)askstheR-STStoshowaWebpageinwhichtheusercanpickhisownrealmamongthelistofalltrustedIPs.Thisisoftenagoodsolution,buttherearesituationsinwhichitisnotadvisabletorevealthelistofalltrustedIPs.Furthermore,sometimesaskingtheusertomakeachoiceisinconvenientorunacceptable,inwhichcasetheIPselectionshouldbedonesilentlyaccordingtosomecriteria.

WS-FederationprovidesaparameterthatcanbeusefulinhandlingHRD:whr.Itismeanttocarrytheaddress(ortheurn:identifier)ofthehomerealm.AnR-STSreceivingawsignin1.0messagethatincludeswhrwillconsiderwhrcontenttobetheIP-STSoftherequestorandwilldrivethesequenceaccordingly.(SeeFigure4-9.)

Browser

IP-STS A

APP

1

23 4

6

7

Trust

Trust

R-STS

IP-STS B

Trust

WHR=http://A

5

FIGURE4-9 TheHomeRealmDiscoveryproblem

Page 68: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 137

1 TheuserrequestsapagefromApp.

2 Becausetheuserisnotauthenticated;instead,heisredirectedtoR-STSforauthenti-cation.Thesign-inmessageincludesanewparameter,whr,whichindicatesAasthehomerealmfortherequest.

3 R-STSredirectstherequesttoA.

4 OncetheusersuccessfullyauthenticateswithA,hegetsbackatoken.

5 TheusergetsredirectedbacktoR-STS,whichvalidatesthetokenfromAandconsiderstheuserauthenticatedthankstoit.

6 R-STSissuesatokentotheuser,asrequested.

7 TheusergetsbacktoAppwiththetokenobtainedfromR-STSasrequired,andtheauthenticatedsessionstarts.

Whoinjectsthewhrvalueintheauthenticationflow?Thereareatleasttwopossibilities:

■ Therequestor YoucanimagineascenarioinwhichtheadministratoroftheorganizationofIPAgivestoallusersalinktotheRPthatalreadycontainsthewhrparameterpreselectingIPA.Thatisahandytechnique,whicheliminatedtheHRDproblematitsroot.Unfortunately,thisisnotguaranteedtowork:thissystemrequirestheRPtounderstand(oratleastpreserveintheredirecttotheR-STS)thewhrparam-eter,butWS-FederationdoesnotmandatethistotheRP.Infact,RPsimplementedviaWIFdonotsupportthisbehavioroutofthebox(althoughit’snotespeciallyhardtoaddit).

■ TheRP TheRPitselfcouldinjectwhrinthemessagetotheR-STS.ImaginethecaseinwhichtheRPisonespecificinstanceofamultitenantapplication.Inthatcase,thewhrmightbeoneoftheparametersthatpersonalizetheinstanceforagiventenant.WIFsupportsthisspecificsetupontheRP,byallowingyoutospecifytheattributehomeRealminthe<federatedAuthentication/wsFederation>elementoftheWIFcon-figuration.ThevalueofhomeRealmwillbesentviawhrtotheR-STS.However,theWIFSTStemplateprojectknowsnothingaboutwhrandwilljustignoreit.Onceagain,itisnothardtoaddsomehandlinglogic.

TheR-STSistherecipientofwhr.IftheexecutionreachestheFPwithouthavingaddedawhr,itisuptotheR-STStomakeadecisiononthebasisofanythingelsethatisavailableinthespecificsituationandcanhelpdecidewhichIPshouldbechosen.

Let’sonceagainsetupahypotheticalsolutioninVisualStudiosothatyoucangainhands-onexperiencewiththeflowthescenarioentails.

Ifyoustillhavethesolutionweusedforshowinghowfederationworks,right-clickonBasicWebSite_STS,andagainusetheAddSTSReferenceWizardtooutsourceitsauthentica-tiontoanewSTS.VisualStudiowillcallthenewSTSBasicWebSite_STS_STS1.ThecurrentsituationisdescribedinFigure4-10.

Page 69: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

138 Part II Windows Identity Foundation for Identity Developers

FIGURE4-10 ThesamplesolutionshowinghowtohandleHRD

BasicWebSitetrustsBasicWebSite_STS,theR-STSofthescenario.BasicWebSite_STSnowtrustsBasicWebSite_STS_STS1becausewiththelatestaddSTSreference,itsformertrustrelationshipwithBasicWebSite_STS_STShasbeenoverridden.ThegoalhereistoestablishamechanismthatallowstheflowtoswitchbetweenthetwoIPsinthescenario(BasicWebSite_STS_STSandBasicWebSite_STS_STS1)dynamically.

Note WithallthoseSTSeslookingalike,thingsmightbecomehardtofollow.Agoodtrickforalwaysknowingwhatisgoingonisassigningdifferentcolorstothebackgroundofthelogin.aspxpagesofthevariousSTSprojects.

TheeasiestthingtoaccomplishinthescenarioisenablingtheRPBasicWebSitetoexpressapreferenceforoneIPviawhr.Asmentionedearlier,thiscanbedoneeasilyviaconfiguration:

<federatedAuthentication> <wsFederation passiveRedirectEnabled=”true” issuer=”https://localhost/BasicWebSite_STS/” realm=”https://localhost/BasicWebSite/” homeRealm=”https://localhost/BasicWebSite_STS_STS/” requireHttps=”true” /> <cookieHandler requireSsl=”true” /> </federatedAuthentication>

ThevalueofhomeRealmestablishesthatBasicWebSite_STS_STSshouldbeusedforauthentication,whichiscontrarytowhattheWIFconfigurationofBasicWebSite_STScurrentlysays.Thatway,itwillbeobviouswhetherthesystemsuccessfullyoverridesthestaticsettings.

Note Asisusuallythecasefortheparametersin<wsFederation>,youcandosomethingtothesameeffectbyusingthePassiveFederationSignInControlanditsproperties.Fromnowon,I’llomitthisnote,assumingthatinsimilarsituationsyou’llknowthatthecontrolalternativeisavailable.

ThenextstepismakingtheWIFSTStemplateunderstandwhr.Itisactuallysimple—itismainlyamatterofinterceptingtheredirecttotheIPandforcingittogowheneverthewhr

Page 70: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 139

decides.AddtotheBasicWebSite_STSprojectaglobal.asaxfile.HereyoucanhandletheWSFAMRedirectingToIdentityProvidereventasfollows:

<%@ Application Language=”C#” %> <%@ Import Namespace=”Microsoft.IdentityModel.Web” %> <script runat=”server”> void WSFederationAuthenticationModule_RedirectingToIdentityProvider (object sender, RedirectingToIdentityProviderEventArgs e) { string a = HttpContext.Current.Request.QueryString[“whr”]; if (a != null) { e.SignInRequestMessage.BaseUri = new Uri(a); } }

Thecodecouldnotbeeasier.Itverifieswhetherthereisawhrparameterinthequerystring,andifitthereisone,itassignsittotheBaseUriintheSignInRequestMessage,overwritingwhatevervaluetheBasicWebSite_STSconfigurationhadputinthere.Assoonasthehandlerreturns,theWSFAMwillredirectthesign-inmessagetothewhr—inthiscase,BasicWebSite_STS_STS.Andthatisexactlyasyouwantedit.

Note Thecodehereassumesthatwhrcarriesanetwork-addressableURI,butpertheWS-Federationspecificationthismightnotbethecase.IftheURIisanurnidentifier,BasicWebSite_STSshouldlookuptheactualaddressinsomemappingstore.

HavingtospecifythehomerealmintheRPconfigurationmightbetoostaticabehav-iorformanyoccasions.Fortunately,theRedirectingToIdentityProvidereventcanbeeasilyhandledontheRPaswell,implementinganydynamicbehavior.Forexample,youcanthinkofmaintainingatableofIPrangeswhererequestsmightcomefrom,andmapthemtothecorrespondingIPaddresses.Forthesakeofsimplicity,hereI’llshowyouhowtoimplementtheapproachwhenitistherequestorthatsendsthewhrupfrontinitsfirstrequesttotheRP.

Ifyouaddaglobal.asaxfiletoBasicWebSite,almostexactlythesamecodeasshownearlierwillgiveyouthedesiredeffect:

<%@ Application Language=”C#” %> <%@ Import Namespace=”Microsoft.IdentityModel.Web” %> <script runat=”server”> void WSFederationAuthenticationModule_RedirectingToIdentityProvider (object sender, RedirectingToIdentityProviderEventArgs e) { string a = HttpContext.Current.Request.QueryString[“whr”]; if (a != null) { e.SignInRequestMessage.HomeRealm = a; } }

Page 71: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

140 Part II Windows Identity Foundation for Identity Developers

ThecodehereinterceptstheexecutionrightbeforesendingbacktheredirecttotheR-STS,andiftheoriginalrequestcontainedwhritensuresthatitwillbepropagatedtotheR-STSaswell.ThatmeansyoucandeletethehomeRealmattributeintheBasicWebSiteconfig,becausenowyouhavetheabilitytoexpresswhrdirectlyatrequesttime.

Important Keepinmindthatallthesampleshereaimtohelpyouunderstandtheproblem,buttheydonotconstitutecompletesolutions.HandlingHRDinpracticeisnotjustamatterofcomplyingwiththeprotocol.Instead,itpresentsvariouschallengeswithmanageabilityandmaintenanceaspectsthatarebeyondthescopeofthisbookandarebestaddressedbyusingpackagedserver-gradeproductssuchasADFS2.0.

Step-up Authentication, Multiple Credential Types, and Similar ScenariosThetrickofusingRedirectingToIdentityProviderforsteeringtherequesttotheSTShasmanyapplicationsthatgobeyondtheHRDproblemexaminedearlier.

OneeminentexampleofthisshowsupeverytimetheRPneedstocommunicatesomekindofpreferenceabouttheauthenticationprocesstheIPshouldusewhenissuingtokenstousers.It’sgreatthatclaims-basedidentitydecouplestheRPfromtheauthenticationrespon-sibilities,buttherearesituationsinwhichthevalueoftheoperationimposescertainguar-anteesaboutthestrengthoftheauthentication.ImagineabankingWebsiteoramedicalrecordsWebsitethatgivesaccesstocertainoperationsonlyiftheuserisauthenticatedwithahigh-assurancemethodsuchasX.509certificatesorsimilar.

Asyou’vegrowntoexpect,WS-Federationhasaparameterforthat:wauth.Itissupposedtobeattachedtowsignin1.0messagestocommunicatetotheSTStheauthenticationmethodpreference.Usually,theSTSusesthatforperforminginternalredirectstooneendpointthatissecuredwiththecorrespondingauthenticationtechnique,orsomethingtothateffect(forexample,wiringcustomHttpHandlersorsimilarlow-leveltricks).

Important Iwon’tgointothedetailshereofhowanSTSshouldhandlewauth,mainlybecauseitwoulddosobyleveragingtheauthenticationinfrastructuresratherthanWIFAPIs.ThemainthingtorememberontheSTSsideisthatatokenwilladvertisetheauthenticationmethodthatledtoitsownissuancebythepresenceoftheclaimoftypeClaimTypes.Authentication.

EachRPhasitsowncriteriaforassigningavaluetowauth.SometimesitisablanketpropertyfortheentireWebsite—inwhichcase,itisexpresseddirectlyin<wsFederation>intheau-thenticationTypeattribute.Atothertimes,theuserisgiventhechanceofselecting(directlyorindirectly)fromamongmultiplecredentialtypes.Inyetanothersituation,theremightbelogicthatsilentlyestablisheswhetherthecurrentauthenticationlevelisenoughforaccessingtherequestedresource,orwhetherthesystemshouldstepuptoahigherlevelofassurance

Page 72: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 141

andre-authenticatetheuseraccordingly.Thelasttwocasescallforadynamicassignmentofwauth,whichiswhenreusingwhatyoulearnedaboutwhrandRedirectingToIdentityProvidercomesinhandyforwauthtoo.

AuthenticationMethodsWIFoffershandyconstantsrepresentingcommonauthenticationmethods.Onceagain,theyaregroupedinmultiplecollections:Microsoft.IdentityModel.Claims.AuthenticationMethodsandMicrosoft.IdentityModel.Tokens.Saml11.Saml11Constants+AuthenticationMethods(shownnext).TheSDKsamplesusethefirstone,whereasthesecondoneisusedwhencommunicatingwithADFS(thoughinthatcase,itboilsdowntoPassword,TlsClientString,andWindowsString).Infact,thevaluesinthefollowingAuthenticationMethodsareonlyusedintheon-the-wireformatspecifiedbySAML.Inthegeneralcaseyouwon’tneedthem.

public static class AuthenticationMethods { // Fields public const string HardwareTokenString = "URI:urn:oasis:names:tc:SAML:1.0:am: HardwareToken"; public const string KerberosString = "urn:ietf:rfc:1510"; public const string PasswordString = "urn:oasis:names:tc:SAML:1.0:am:password"; public const string PgpString = "urn:oasis:names:tc:SAML:1.0:am:PGP"; public const string SecureRemotePasswordString = "urn:ietf:rfc:2945"; public const string SignatureString = "urn:ietf:rfc:3075"; public const string SpkiString = "urn:oasis:names:tc:SAML:1.0:am:SPKI"; public const string TlsClientString = "urn:ietf:rfc:2246"; public const string UnspecifiedString = "urn:oasis:names:tc:SAML:1.0:am: unspecified"; public const string WindowsString = "urn:federation:authentication:windows"; public const string X509String = "urn:oasis:names:tc:SAML:1.0:am:X509-PKI"; public const string XkmsString = "urn:oasis:names:tc:SAML:1.0:am:XKMS"; }

TheWS-Federationspecificationlistsyetadifferentsetofwst:AuthenticationType values,buttobefairitexplicitlystatesthatthosetypesareoptional.

ClaimsProcessingattheRPInthisfinalsectionofthechapter,Icoversomeofthethingsyoucandowithclaimsatthelastminute,whentheyarealreadyintheRPpipelineandareabouttohittheapplicationcode.

Thereisnotawholelotofcodingrequired,especiallyconsideringthatIalreadycoveredClaimsAuthorizationManagerindetailinChapter2.Thissectionattemptstogiveyouanideaoftheintendedusageofthoseextensionpointsandinspireyoutotakeadvantageoftheminyourscenarios.

Page 73: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

142 Part II Windows Identity Foundation for Identity Developers

AuthorizationClaimsauthorizationisafascinatingsubjectthatprobablydeservesanentirebookofitsown.OnethingthatputsoffthevariousRole-BasedAccessControl(RBAC)aficionadosisthatthereissomuchfreedomandsomanywaysofdoingthings.Forexample,takethecoarseformofauthorizationthatcanbeimplementedbysimplyrefusingtoissueatoken.YoucansetuprulesattheIPthatpreventfromobtainingatokenalltheusersthatarealreadyknownnottobeauthorizedtoaccesstheapplicationtheyareaskingfor.ThatisfeasibleforallthesituationsinwhichtheIPknowsenoughtomakeadecision—forexample,incaseslikeCustomerRelationshipManagement(CRM)online,inwhichusersneedtobeexplicitlyinvitedbeforehavingaccess,evenwhenthere’safederationinplace.

AnotherobviousplaceforenforcingauthorizationisintheR-STS,whichmightdenytokensonthebasisofsomecross-organizationalconsiderations.Forexample,theR-STSusedbyoneindependentsoftwarevendor(ISV)formanagingaccesstoitsapplicationportfoliomightkeeptrackofhowmanyconcurrentusersarecurrentlyholdingactivesessionsandrefusetoissueanewtokenifthatwouldexceedthenumberoflicensesboughtbytheIPorganization.

TheenforcementpointthatistheclosesttotraditionalauthorizationsystemsistheRPitself,whichiswhereClaimsAuthorizationManagerispositioned.Thereareintrinsicadvantagestoenforcingauthorizationhere.Theresourcesarewellknown.Forexample,iftheRPisadocu-mentmanagementsystem,thelifecycleofdocumentsthemselvesisunderthecontroloftheRP,whichcaneasilymanagepermissionsaswell;whereasothers(suchastheR-STS,orworsestill,theIP)wouldneedtobesynchronized.Anotheradvantageistheavailabilityofthecallitself,althoughthat’seasiertoseewithWebservicesthanwithWebsites.Ifyouwanttoauthorizetheusertomakeapurchaseaccordingtoaspending-limitclaim,youneedboththeclaimvalueandtheamountoftheproposedpurchase:oneSTSwouldonlyseetheclaimvalue,asthebodyofacallplaysnopartinRST/RSTRexchanges.

TheabsoluteflexibilityofferedbyClaimsAuthorizationManagerisbothitsgreateststrengthandbiggestweakness.Claims-basedauthorizationisreallypowerful,butatthetimeofthiswritingtherearenoout-of-the-boximplementationsofClaimsAuthorizationManagerortoolsandofficialpolicyformatsforit.Youcandoeverythingwithit,butyouarerequiredtowriteyourowncode.

Authentication and Claims ProcessingSometimesitjustmakessensetodosomeclaimsprocessingattheRPside.PerhapsyouneedtomakeavailabletotheapplicationcodeinformationabouttheuserthatisknowntotheRPbutnottotheR-STS,suchasinthecaseofauserprofilespecifictotheapplication.Ormaybethereareclaimsyouneedtoseeonlyonce,atthebeginningofthesession,butthatyouprefernottomakeavailabletotheapplicationcode.

Page 74: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

Chapter 4 Advanced ASP .NET Programming 143

Fordoinganyofthesethings,WIFoffersyouaspecifichookintheRPpipeline,whichyoucanleveragebyprovidingyourownclaims-manipulationlogicwrappedinacus-tomClaimsAuthenticationManagerclass.ClaimsAuthenticationManagerworksalotlikeClaimsAuthorizationManager:youprovideyourlogicbyoverridingonemethod(hereit’sAuthenticate),andyouaddyourclassinthepipelinebyaddingintheWIFconfigtheelement<claimsAuthenticationManager type=”CustomClaimsAuthnMgr”/>.

InyourimplementationofAuthenticate,youcandowhateveryouwantwiththeprincipal,includingdeletingclaims,addingclaims,orevenusingacustomIClaimsPrincipalimplementation.Hereisasuper-simpleexampleofClaimsAuthenticationManager:

public class CustomClaimsAuthnMgr: ClaimsAuthenticationManager { public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal) { //If the identity is not authenticated yet, keep this principal and let it redirect to the STS if (!incomingPrincipal.Identity.IsAuthenticated) { return incomingPrincipal; } ((IClaimsIdentity)incomingPrincipal.Identity).Claims.Add( new Claim(ClaimTypes.Country,"Saturn,"ClaimValueTypes.String,"LOCAL AUTHORITY")); return incomingPrincipal; } }

Inthiscase,thecodesimplyaddsanextraclaimtotheprincipal.Notethattheissuerisassignedto“LOCALAUTHORITY.”Youcanuseprettymuchanythingyouwanthere,butyoushouldreallyavoidusinganexistingissueridentifierbecauseitisequivalenttopretendingtobealegitimateissuer.

SummaryWow,thatwasanintensechapter!IhopeyouhadasmuchfunreadingitasIhadwritingit.

ThischaptertookamuchmoreconcreteapproachtoWIFprogramming,leveragingtheprogrammingmodelknowledgeyouacquiredinChapter3totacklemanyimportantproblemsandscenariosyoumightencounterwhensecuringASP.NETapplications.

YoulearnedaboutthedistinctionbetweenidentityprovidersandFederationProviders,acquiringfamiliaritywiththeWIFSTStemplateintheprocess.

Youfinallysawappliedinpracticethesign-inflowstudiedinChapter3,applyingittothecaseofmultipleWebsitesanddiscoveringhowtheunderlyingstructuremakesSSOpossible.YouhadachancetolearnhowSingleSign-outworks,andhowtouseWIFforimplementing

Page 75: Sample Chapters from Programming Windows Identity …download.microsoft.com/.../9780735627185_SampleChapters.pdf4 Part I Windows Identity Foundation for Everybody The problem of recognizing

144 Part II Windows Identity Foundation for Identity Developers

itinafewlinesofcode.Weexploredonecaseofexoticsessionmanagement,inwhichthevalidityisdrivenbyuseractivityratherthanfixedexpirationtimes.

Theclassicfederationcaseandhomerealmdiscoveryarenowveryconcretescenariosforyou,andyouknowwhatittakesfordealingwiththeminvarioussituations.Intheprocessoflearningthis,youalsogainedfamiliaritywithWIF’sobjectmodelforclaims.

Finally,youhadachancetotieupafewlooseendsregardingtheuseofClaimsAuthenticationManagerandClaimsAuthorizationManagerforprocessingclaimsoncetheyhavealreadyreachedtheRP.

IfyoudevelopfortheASP.NETplatform,thischaptershouldhaveequippedyouwithalltheknowledgeyouneedfortacklingthemostcommonproblemsandthensome.Foranythingnotexplicitlycoveredhere,youshouldnowbeabletoinvestigateandsolveissuesonyourown.

Inthenextchapter,I’llturntoWebservicesandexplorehowWIFandWCFcanworktogethertocreatesaferapplicationswhiledeliveringakillerdevelopmentexperience.