Programming Windows Identity eBook -...

102

Transcript of Programming Windows Identity eBook -...

Page 2: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

Programming Windows® Identity Foundation

Vittorio Bertocci

Page 3: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

PUBLISHED BYMicrosoft PressA Division of Microsoft CorporationOne Microsoft WayRedmond, Washington 98052-6399

Copyright © 2011 by Vittorio Bertocci

All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher.

Library of Congress Control Number: 2010933007

Printed and bound in the United States of America.

Distributed in Canada by H.B. Fenn and Company Ltd.

A CIP catalogue record for this book is available from the British Library.

Microsoft Press books are available through booksellers and distributors worldwide. For further infor mation about international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly at fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send comments to [email protected].

Microsoft and the trademarks listed at http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies. All other marks are property of their respective owners.

The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.

This book expresses the author’s views and opinions. The information contained in this book is provided without any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.

Acquisitions Editor: Ben RyanDevelopmental Editor: Devon MusgraveProject Editor: Rosemary CapertonEditorial Production: Waypoint Press (www.waypointpress.com)Technical Reviewer: Peter Kron; Technical Review services provided by Content Master, a member of CM Group, Ltd.Cover: Tom Draper Design

Body Part No. X17-09958

Page 4: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

To Iwona, moja kochanie

Page 5: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a
Page 6: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

v

Contents at a Glance

Part I WindowsIdentityFoundationforEverybody 1 Claims-Based Identity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2 Core ASP .NET Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Part II WindowsIdentityFoundationforIdentityDevelopers

3 WIF Processing Pipeline in ASP .NET . . . . . . . . . . . . . . . . . . . . . . . . 51 4 Advanced ASP .NET Programming . . . . . . . . . . . . . . . . . . . . . . . . . 95 5 WIF and WCF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 6 WIF and Windows Azure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 7 The Road Ahead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

Page 7: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a
Page 8: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 9: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 10: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 11: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 12: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

xi

ForewordAfewyearsago,IwassittingatatableplayingagameofpokerwithafewcolleaguesfromMicrosoftwhohadallbeeninvolvedatvarioustimesinthedevelopmentofWebServicesEnhancementsforMicrosoft.NET(WSE).DonBox,MarkFussell,KirillGavrylyuk,andIplayedthehandswhileshowmanextraordinaireDougPurdyengageduswithlivelybanterandmorethanafewquestionsabouttheproduct—allofthisinfrontofthecamerasattheMSDNstudios.

Wehadeachselectedapersonfromthefieldtoplayfor;someonewhomweeachthoughthadmadeasignificantcontributiontothesuccessofWSEbuthadn’tbeenadirectmemberoftheproductteamitself.Ifwewon,thenournomineewouldgetaprize,atokenofourappreciationfortheworkthatheorshehaddone.MyselectionwasaguycalledVittorioBertocciwhowasworkingforMicrosoftinItalyatthetime.I’dnevermetVittorio,norevenseenaphotoofhim,buthewasaprolificposteronourinternaldiscussionlist,clearlyunderstoodthekeysecurityconceptsfortheproductincludingtheWS-*protocols,andhadevencraftedanextensiontoenableReliableMessagingdespitesomeofthecrudeextensibilitywehadinplaceatthetime.Vittoriowassomeoneworthplayingforbut,unfortunately,Ididn’twin.

Timepassed,theWindowsCommunicationFoundation(WCF)supersededWSE,andImovedtobecometheArchitectfortheIdentityandAccessteamtaskedwithbuildingaSecurityTokenServiceforWindowsServer.Oneday,outoftheblue,Igotane-mailfromVittoriotosaythathe’dmovedtoRedmondtotakeonaPlatformEvangelistroleandaskingifwecouldmeetup.OfcourseIsaidyes,butwhatIcouldn’thaveanticipatedwasthatmaneofjet-blackhair....

Vittoriowasdeeplyinterestedintheworkthatweweredoingtoenableaclaims-basedprogrammingmodelfor.NET,ontopofwhichweplannedtobuildthesecondversionofoursecuritytokenservice.Overtime,theseideasbecamethe“Geneva”waveofproductsandwerefinallybirthedastheWindowsIdentityFoundationandActiveDirectoryFederationServices2.0.

Throughoutseveralyearsofproductdevelopment,Vittoriobecamenotonlyaremarkablespokespersonfortheproductsbutakeysourceoffeedbackonourwork,bothfromthecustomersandpartnersthathemetwithandfromhisowndirecteffortstousetheproduct.Hewasinstrumentalinencouragingme,andtheproductteam,totakeonthelast-minutetaskofmakingWIFruninWindowsAzurejustintimeforPDC2009andtheproductrelease.WatchingVittoriopresentasessiononWIFisapleasure—hisdepthofknowledgeandhiscreativepresentationskillsallowhimtodeliverthemessageonanincreasinglyimportanttopicdespitethefactthatitistoofrequentlytaintedwiththedrynessofthe“security”label.

Page 13: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

xii Foreword

Withinthepagesofthisbook,you’lllearnhowtousetheWindowsIdentityFoundationfromsomeonewhoisnotonlyagreatteacherbutisalsodeeplyfamiliarwiththeconceptsbe-hindthetechnologyitselfandwhohasworkeddirectlywiththeproductteam,andmyselfpersonally,onaveryclosebasisoverthecourseofthelastfourtofiveyears.

Vittoriotakesyouthroughtheterminologyandkeyconcepts,andexplainstheintegrationofWIFwithASP.NET,WindowsCommunicationFoundation,andWindowsAzure,culminat-inginaspeculativelookaheadatthescenariosthattheproductmighttackleinafuturerelease.Iencourageyou,thereader,tothinkdeeplyabouttheconceptshereandhowyouwillmanageidentityintheapplicationsthatyougoontobuild;it’satopicthatisbecomingincreasinglyimportanttobothenterprisesandtheWebcommunity.

Finally,IwanttothankVittorioforhisenthusiasm,support,andtirelessenergyovertheyears.Ihavebutonefinalrequestofhim:pleasegetahaircut.

Hervey WilsonArchitect, AppFabric Access Control Service

Microsoft, RedmondJuly 2010

Page 14: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

xiii

AcknowledgmentsYou create the world of the dream. We bring the subject into that dream and fill it with their subconscious.

—Cobb in “Inception”, Christopher Nolan, 2010

Sometimeago,afriendaskedmewhatthepointwasofwritingabookwhenIalreadyhaveawell-readblog.Therearemanyexcellentanswerstothatquestion,fromtheextrareachthatabookhastotheadvantagesofreadingwithouthavingtoconstantlyfighttheop-portunitycostsofnotfollowingalink.Myfavoriteanswer,however,isthatwhereasablogisaone-manoperation,abookistheresultofthecontributionofmanypeopleanditsvalueforthereaderisproportionallyhigher.Itmightbemynameonthecover,buttherealityisthatIstandontheshouldersofmanyfinepeople,whoIwanttoacknowledgehere.I’vebeenworkingwithidentityforthelast8yearsorso,interactingwithanincredibleamountofpeople;hence,IamprettysureI’llforgetsomebody.Iapologizeinadvance.

PeterKronisaPrincipalSoftwareDeveloperEngineerontheWIFteam,andtheofficialtechnicaleditorofthisbook.Withouthispatience,thoroughness,anddeepknowledgeofWIF,thiswouldhavebeenamuchinferiorbook.

HerveyWilsonistheArchitectoftheAccessControlservice.HeledtheWebServicesEnhancements(WSE)team,andhehappenstobetheonewhoenvisionedWindowsIdentityFoundation.I’vebeenworkingwithHerveysince2002,wellbeforeImovedtoRedmond.Atthetime,IwasstillusinghisWSEforsecuringsolutionsforItaliancustomers.IfyoubelievewhatMalcomGladwellsaysinhisbookOutliers: The Story of Success(Little,BrownandCo.,2008),thatyouneed10,000hoursofpracticeforbecomingrealgoodatsomething,nobodycontributedmorethanHerveytomyprofessionalgrowthinthefieldofIdentity.Iamveryhonoredheagreedtowritetheforewordforthisbook.Thanks,man!

ThecrewatMicrosoftPresshasbeenoutstanding,choppingintomanageablechunksmylong“Itanglish”sentenceswithoutchangingthemeaningandworkingaroundmyabysmaldelaysandcrazyschedule.(Inthelastyearalone,Ihandedaboardingpasstosmilingladies55times.)Specifically,thanksgotoBenRyanandGerryO’Brienforhavingtrustinmeandthebook,toDevonMusgraveforbootstrappingtheproject,andtoRosemaryCapertonforrunningtheproject.SteveSagmanofWaypointPressledafantasticproductionteam:RogerLeBlancasCopyEditor,ThomasSpeechesasProofreader,andAudreyMarrasIllustrator.SpecialthankstoAudreyforworkingonreallychallengingillustrations:youcanpullouttheneedlesfrommydollnow!

StuartKwan,GroupProgramManagerforWIF,andConradBayer,GMfortheIdentityandAccessdivision,havebeengreatpartnersandsupportedthisprojectfromtheverystart.

Page 15: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

xiv Acknowledgments

Ididmostofthewritingatnight,onweekends,andduringvacationtime,butattimesthebookdidimpactmydayjob.JamesConardandNeilHutson,SeniorDirectorsintheDeveloperandPlatformEvangelismgroupandmydirectmanagementchain,havebeenverypatientandsupportiveoftheeffort.

JustineSmithandBrjannBrekkan,fromtheBusinessGroupoftheIdentityandAccessDivision,havebeenincrediblyhelpfulonactivitiesthatultimatelyhadanimpactonthesamplecodediscussedhere.

ToddWest,atthetimewiththeWIFtestteam,isoneofthemostgiftedWebservicesdevelopersI’veevermet.MostoftheguidanceregardingWIFandWindowsAzureinthisbookandoutthereistheresultofhiswork.

MygoodfriendCalebBaker,ProgramManagerontheWIFteam,isanever-endingsourceofinsightsandusefuldiscussions.HeisalsotheowneroftheWIFandSilverlightintegration.TheSilverlightcodesamplesareallbasedonhiswork.

TogetherwithHervey,theoriginalWSEteammergedwithWIFtoo.Ihadachancetotaptheirbrainscountlesstimes.ThankstoSiddShenoy,GovindRamanathan,VickMukherjee,HongMeiGe,andKeithBallinger.

TheentireWIFteamcontributedtothisbook.HereI’llcallafewpeopleouttogiveyouafeelingforthequalityoftheirwork.DanielWuwasofgreathelponsessions;BrentSchmaltzwaskeyforhelpingmeunderstandtheinnerworkingsofWIFandWCF;VaniNoriandVickdevisedthewayofusingWIFwithMVC;JunaidTisekarwaskeyforstartingtheworkwithWIFandOAuth2.0;ShiungYongwasinstrumentalinfiguringoutsomepartsoftheWIFpipelineintheearlydaysofWIF.

Manyothersintheidentityproductteamcontributedthroughtheyears:thankstoJanAlexander,VijayGajjala,ArunNanda,MarcGoodner,MikeJones,CraigWittenberg,DonSchmidt,RuchiBhargava,SeshaMani,MattSteele,andSamDevasahayam.

MyteammatesintheWindowsAzureplatformevangelismteamplayedakeyroleinkeepingmeonmytoes,andthey’resimplyawesometohangoutwith.ThankstoRyanDunn,DavidAiken,NigelWatling,andZachOwen.Pleasedeleteallthepicturesyousaved!

TheguysatSouthworks,thecompanythathelpedmewithpracticallyalltheidentitysamplesandlabsinthelasttwoyears,arefantastictoworkwith.ManythankstoMatiasWoloski,PabloDamiani,TimOsborn,JohnnyHalife,andmanyothers.

ConversationsaboutidentitywithGianpaoloCarraroandEugenioPacewereextremelyvaluable,especiallytheonesrelatedtotheP&Pguideonclaims-basedidentityledbyEugenio.

Page 16: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

Acknowledgments xv

DonovanFollettehasbeentheADFSevangelistforalongtime,sharingwithmethepainsandthejoysoftheclaims-basedidentityrenaissanceatPDC08.EvenifnowheisallcozyinhisnewOfficerole,Icannotforgethisincrediblecontributiontobringingidentitytothecommunity.

Ofcourse,wewouldnotbeevendiscussingthisifKimCameronhadnotdriventheconversationontheidentitymetasystemandclaims-basedidentitywiththeentireindustry.Thankyou,Kim!

Mywife,IwonaBialynicka-Birula,deservesspecialthanks.Sheacceptedandsupportedthiscrazyinitiativenomatterwhat,whetheritmeantskippingbeachtimewhileinMauiorcopingwithinsuranceagentsandcontractorsafterourhousegotflooded.Withouther,notonlywouldyounotbeholdingthisbookinyourhands,Idon’tknowwhatIwoulddo….Thankyou,darling.Ipromise:nomorebooksforsometime!

Finally,Iwanttothankyou:thereadersofmyblog,whofollowedfaithfullymyramblingsforsevenyearswithoutaskingtoooftenabouttheweirdblogname;theparticipantsoftheWIFworkshopsinBelgium,UK,Germany,Singapore,Melbourne,andRedmond,whoputupsonicelywithmy“sexy”accent;andtheattendeesofthemanysessionsIgaveateventsallovertheworldinthelastfiveyears.Withoutyourquestions,yourcritiques,yourcomments,yourcompliments,andyourlongingforunderstanding,IwouldhaveneverfoundthemotivationtodothisandtheotherthingsIdoforevangelizingidentity.Thisbookisforyou.

Page 17: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

xvii

IntroductionIthasbeensaidthateveryprobleminComputerSciencecanbesolvedbyaddingalevelofindirection.

Youdon’thavetogofartofindexamplesofsuccessfulapplicationsofthatprinciple.Beforetheintroductionoftheconceptofdriver,programshadtoberewritteneverytimeonechangedsomethingassimpleasthemonitor.BeforetheintroductionofTCP/IP,programstargetingatokenringnetworkenvironmenthadtoberewrittenifthenetworkprotocolchanged.DriversandTCP/IPhelpedtofreeapplicationdevelopersfromtheneedtoworryaboutunnecessarydetails,presentingthemwithagenericfaçadewhileleavingthenitty-grittydetailstotheunderlyinginfrastructure.Inadditiontomakingthedeveloperprofessionahappierone,theapproachledtomorerobustandlong-livedsoftwareforthebenefitofeverybody.

Forvarioushistoricalreasons,authenticationandidentitymanagementpracticesneverreallyfollowedthesamerouteofmonitorsandnetworkcards.Adding“authentication”toyoursoftwaretodaystilllargelymeansmessingwiththecodeoftheapplicationitself,writinglogicthattakescareindetailoflowleveltaskssuchasverifyingusernameandpasswordsagainstanaccountstore,jugglingwithX509certificatesorsimilar.Whenyouaresparedfromhandlingthingsatsuchlowlevel,whichusuallymeansthatyoutookastrongdependencyonyourinfrastructureandyourapplicationwillbeunmovablewithoutsubstantialrewriting:justlikeaprogramfromthepre-driversera.

Asyouwilllearninthefirstchaptersofthisbook,claims-basedidentityischangingallthis.

Withoutgoingtoomuchintodetails,claimsarethemeanstoaddthatextralevelofindirectionthateludedtheidentityworldsofar.Theintroductionofopenprotocolsenjoyingwideindustryconsensus&support,theconvergetowardtheideaofameta-systemforidentity,thesuccessofmetadataformatswhichcanautomatemanytediousanderror-pronetaskscreatedtheperfectstormthatgeneratedthepracticescollectivelyknownasclaims-basedidentity.Claimsarepavingthewayforidentityandaccessmanagementtobepushedoutsideofapplicationsanddownintheinfrastructure,freeingdevelopersfromtheneedtohandleitexplicitlywhileenhancingsolutionswithwelcomeextraadvantages(suchascross-platforminteroperabilityoutofthebox).

Ihavespentfullfouryearsworkingalmostexclusivelyonclaims-basedarchitectureswithcustomersandproductteamshereinRedmond;themodelissound,anditinvariablydeliverssignificantimprovementsagainstanyotherauthenticationsystem.However,untilrecently,actuallyimplementingsystemsaccordingtothemodelwasapainfulexperience,sinceitrequiredwritinglargeamountsofcustomcodethatwouldhandleprotocols,cryptography,andsimilarlowlevelaspects.

Page 18: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

xviii Introduction

Thisallchangedwhen,inOctober2008,Microsoftannouncedthe“Geneva”waveofclaims-awarebetaproducts:amongthosetherewasWindowsIdentityFoundation,theprotagonistofthebookyouareholding,whichwasfinallyreleasedinNovember2009.

WindowsIdentityFoundation(WIF)isMicrosoft’sstackforclaims-basedidentityprogramming.Itisanewfoundationaltechnologywhichhelps.NETdeveloperstotakeadvantageoftheclaimsbasedapproachforhandingauthentication,authorization,custom-izationandingeneralanyidentity-relatedtaskwithouttheneedtowriteanylow-levelcode.

Truetotheclaims-basedidentitypromise,youcandecidetouseWIFtoexternalizeallidentityandaccesscontrollogicfromyourapplications:VisualStudiowillmakeitabreeze,andyouwillnotberequiredtoknowanydetailabouttheunderlyingsecurityprotocols.Ifyouwanttotakefinercontroloftheauthenticationandauthorizationprocess,however,WIFoffersyouapowerfulandflexibleprogrammingmodelthatwillgiveyoucompleteaccesstoallaspectsoftheidentitymanagementpipeline.

ThisbookwillshowyouhowtouseWindowsIdentityFoundationforhandlingauthentication,authorizationandidentity-drivencustomizationofyour.NETapplications.

Althoughthetextwilloftenbetask-oriented,especiallyforthenovicepartofthebook,theultimategoalwillalwaysbetohelpyouunderstandingtheclaimsbasedapproachandthepatternthatismostappropriatefortheproblemathand.

WhoIsThisBookFor?PartIofthebookisfortheASP.NETdeveloperwhowantstotakeadvantageofclaims-basedidentitywithouthavingtobecomeasecurityexpert.Althoughtherearenorequirementsaboutpre-existingsecurityknowledge,youdoneedtohavehands-onASP.NETprogram-mingknowledgetoproficientlyreadPartI.

InPartIIIshiftgearprettydramatically,assumingthatyouareanexperienced.NETdeveloperwhoknowsaboutASP.NETpipeline,Formsauthentication,X.509certificates,LINQsyntaxandthelike.Ioftentrytoaddsidebarswhichintroducethetopicifyouknowlittleaboutitbutyouwanttofollowthetextanyway,butrealityisthatwithoutconcrete,hands-onknowledgeofthe.NETFramework(andspecificallyC#)PartIIcouldbehardtonavigate.Ialsoassumethatyouaremotivatedtoinvestenergyonunderstandingthe“why”sofidentityandsecurity.

Identityisanenablingtechnology,whichisneverfoundinisolationbutalwaysasacomponentandenhancementofothertechnologiesandscenarios.ThisbookdiscusseshowtoapplyWIFwithavarietyoftechnologiesandproducts,andofcoursecannotaffordprovidingintroductionsforeverything:inordertobeabletoapplytheguidanceinthevariouschaptersyou’llneedtobeproficientinthecorrespondingtechnology.Thegoodnewsisthatthechaptersarereasonablydecoupledfromeachother,sothatyoudon’tneed

Page 19: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

Introduction xix

tobeaWCFexpertforappreciatingthechaptersaboutASP.NET.Chapter3andChapter4requireyoutobefamiliarwithASP.NETanditsextensibilitymodel.Chapter5isforexperi-encedWCFdevelopers.Chapter6requiresyoutobefamiliarwithWindowsAzureanditsprogrammingmodel.Chapter7sweepsonanumberofdifferenttechnologies,includingSilverlightandASP.NETMVCFramework,andexpectsyoutobeateasewithterminologyandusage.

Thebottomlineisthatinordertofullytakeadvantageofthebookyouneedtobeanexpert.NETandWebdeveloper.Ontheotherhand,thebookcontainsalotofarchitecturalpatternsandexplanationswhichcouldeasilybeappliedtoproductsonotherplatforms:henceifyouareanarchitectthatcanstomachpatternsexplanationsintertwinedwithcodecommentary,chancesarethatyou’llfindthisbookagoodreferenceonhowclaims-basedidentitysolvesvariouscanonicalproblemsintheidentityandaccessspace.

SystemRequirementsYou’llneedthefollowingsoftwareandhardwaretobuildandrunthecodesamplesforthisbook:

■ Microsoft®Windows7;WindowsServer2003ServicePack2;WindowsServer2008R2;WindowsServer2008ServicePack2;WindowsVista

■ WindowsIdentityFoundation1.0runtime

■ WindowsIdentityFoundationSDK4.0

■ Microsoft®InternetInformationServices(IIS)7.5,7.0or6.0

■ Microsoft®.NETFramework4.0

■ VisualStudio2010

■ 1.6-GHzPentiumorcompatibleprocessor

■ 1GBRAMforx86

■ 2GBRAMforx64

■ Anadditional512MBRAMifrunninginavirtualmachine

■ DirectX9–capablevideocardthatrunsat1024×768orhigherdisplayresolution

■ 5400-RPMharddrive(with3GBofavailableharddiskspace)

■ DVD-ROMdrive

■ Microsoftmouseorcompatiblepointingdevice

■ Approximately78MBofavailableharddiskspacetoinstallthecodesamples

Page 20: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

xx Introduction

NotethattheWIFruntimeandtheWIFSDK3.5arecompatiblewithVisualStudio2008andthe.NETFramework3.5SP2.TheMarch2010versionoftheIdentityTrainingKitcontainsmostofthesamplesofthebookinaformthatiscompatiblewithVS2008andthe.NETFramework3.5,howeverpleasenotethatthecodeinthetextreferstoVS2010andtherearesmalldifferenceshereandthere.

CodeSamplesThecodesamplesforthisbookareavailablefordownloadhere:

http://www.microsoftpressstore.com/title/9780735627185.

Clickthedownloadlinkandfollowtheinstructionstosavethecodesamplestoyourlocalharddrive.

ThecodesamplesusedinthisbookaremostlyfromtheIdentityDeveloperTrainingKit,acollectionofhands-onlabs,presentations,andinstructionalvideos,whichismeanttohelpdeveloperslearnMicrosoft’sidentitytechnologies.Itisaself-extracting.EXE.Everylabhasitsownsetup,whichwilltakecareofmostprerequisitesforyou.PleasefollowtheinstructionsontheWelcomepage.

ProducingtheIdentityDeveloperTrainingKitisoneofthethingsIdoduringmydayjob.WhereasinthebookIhighlightcodesnippetstohelpyouunderstandthetechnology,intheIdentityDeveloperTrainingKitdocumentationIgivestep-by-stepinstructions.FeelfreetocombinethetwoapproachesasyourampupyourknowledgeofWindowsIdentityFoundation.

TheIdentityDeveloperTrainingKitisalivingdeliverable;everytimethereisanewver-sionofaproductIupdateitaccordingly.However,Iwanttomakesurethatthecodesamplesreferencedinthebookwillnotbreak.Forthatreason,Iamincludinginthebookcodesamplearchivethecurrentversionofthetrainingkit,June2010,whichwillalwaysbeavailable,evenifIkeepupdatingthetrainingkitinitsoriginaldownloadlocation.

ErrataandBookSupportWe’vemadeeveryefforttoensuretheaccuracyofthisbookanditscompanioncontent.Ifyoudofindanerror,pleasereportitonourMicrosoftPresssite.

1.

2. IntheSearchbox,enterthebook’sISBNortitle.

3. Selectyourbookfromthesearchresults.

4.

5. ClickView/SubmitErrata.

Gotowww.microsoftpressstore.com.

On your book’s catalog page, find the Errata & Updates tab

Page 21: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

Introduction xxi

You’llfindadditionalinformationandservicesforyourbookonitscatalogpage.Ifyouneedadditionalsupport,[email protected].

PleasenotethatproductsupportforMicrosoftsoftwareisnotofferedthroughtheaddressesabove.

WeWanttoHearfromYouAtMicrosoftPress,yoursatisfactionisourtoppriority,andyourfeedbackourmostvaluableasset.Pleasetelluswhatyouthinkofthisbookat:

http://www.microsoft.com/learning/booksurvey

Thesurveyisshort,andwereadeveryoneofyourcommentsandideas.Thanksinadvanceforyourinput!

StayinTouchLet’skeeptheconversationgoing!We’reonTwitter:http://twitter.com/MicrosoftPress.

Page 22: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a
Page 23: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 24: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 25: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 26: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 27: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 28: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 29: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 30: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 31: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 32: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 33: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 34: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 35: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 36: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 37: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 38: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 39: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 40: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 41: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 42: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a
Page 43: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 44: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 45: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 46: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 47: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 48: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 49: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 50: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 51: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 52: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 53: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 54: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 55: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 56: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 57: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 58: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 59: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 60: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 61: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 62: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 63: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 64: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 65: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 66: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 67: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 68: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 69: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 70: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 71: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 72: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 73: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 74: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 75: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 76: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 77: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 78: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 79: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 80: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 81: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 82: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 83: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 84: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 85: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 86: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 87: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 88: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 89: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 90: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 91: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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 92: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

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.

Page 93: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

241

Index

Symbols<applicationService>,86<audienceURI>,85<authorization>elementinthe<system.web>

block,36<behavior>element,157<certificateValidation>,89<certificateValidator>,89<ClaimsAuthenticationManager>,87<ClaimsAuthorizationManager>,87<cookieHandler>,85,88<federatedAuthentication>,85,87<issuerNameRegistry>,86<issuerTokenResolver>,89<maximumClockSkew>,88<microsoft.identityModel>,82,84,155overview,39<service>elements,84

<microsoft.identityModel/Service>structure,86.NETapplications

IIdentity,5IPrincipal,5

.NETFrameworkauthenticationmechanisms,5compatibilitywithWindowsIdentityFoundation,24–47

.NETsecurityiPrincipal,6traditionalapproaches,4

<policy>elements,43<protocolMapping>element,157<saml:Assertion>,66<saml:Conditions>,66<saml:SubjectConfirmation>,67<securityTokenHandlers>,89<serviceTokenResolver>,89<wsFederation>,85,88parameters,88Issuer,85passiveRedirectEnabled,85realm,85requireHttps,85

Aaccessgrants,237ACS.SeeAppFabricAccessControlServiceActAsSTSsupport,177tokens,176

ActAsapproach,173Actioncollection,42activeclients,56,148holder-of-keyconfirmationmethod,151message-basedsecurity,150message-levelsecurityoptions,150

ActiveDirectoryFederationServices2.0,15,32,57

activeSTSendpoints,209activesystems,146Actor property,176AddSTSReference,26ADFS2.SeeActiveDirectoryFederationServices2AdobeFlash,147anonymousauthentication,6App_Code,108App_Codefolder,108AppFabricAccessControlService(ACS),204ASP.NET,52authorization,36HttpModules,73integrationwithWIF,52rolesandauthorizationcompatibility,36WIFprocessingpipeline,58

ASP.NETDevelopmentServer,105ASP.NETmembershipprovider,35ASP.NETMVCframework,216

AccountController class,217Authorize,217flow,216–240HttpModules,218login,219LogOnCommon,221logout,220projecttemplate,217web.config,addingWIF,218WIFintegrationsolutions,216–240

ASP.NETSecurityTokenServiceWebSitetemplate,104

Page 94: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

242

ASP.NETSTS.SeeSTSASP.NETWebsites,linkingtoanSTS,26audienceverification,193AuthenticateRequest event,75,76,78authenticationadvantagesofastandardinterface,97externalizing,16,24–47genericsystem,11methodsinWIF,141.NETFramework,5real-world,9step-up,140traditionalapproaches,4

authenticationAPIs,6authenticationlevelverificationoftokens,64authenticationmodesanonymous,6Forms,7Windows,6

authorization,33–46cachinguserdata,34claims,142groupsandroles,35IsInRole,36real-world,9traditionalapproaches,34

AuthorizeRequestevent,75,77Azure.SeeWindowsAzure

Bbearertokens,65,147blacklists,98bootstraptokens,172–184browser-basedpassivesystemsvs.active

systems,147

CCAM.SeeClaimsAuthorizationModuleCanReadKeyIdentifier/CanWriteKeyIdentifier,93CanReadToken,93CanValidateTokenproperty,93CanWriteTokenproperty,93CheckAccessmethod,42Claimclass,130claims,12ADFS2.0claims-transformationlanguage,135ADFS2.0managementUI,112vs.attribute,12authorization,142

customizingUI,37hard-coded,110InformationCardFoundationWebsite,133injectingnew,129,135modification,129,135Name,110pass-through,129,134processingattheRP,141–142processingusingFederationProviders,100Role,110transforming,100,129types,111,133typesandvalueconstants,131

ClaimsAuthenticationManager,92,143ClaimsAuthorizationManager,42,142ClaimsAuthorizationModule,73,92claims-basedauthorization,142claims-basedidentity,3–21advantages,4asalogicallayer,11needfor,4

claims-basedsecurity,147claimsobjectmodel,146–184ClaimsTypesRequested,70ClaimType,72ClaimTypeproperty,19ClaimTypesOffered,72ClaimTypesRequested,72classes,90client-sidefeatures,170–184client-to-STScommunications,180cloud,185–213communicatingacrosssilos,55communicationprotocolsandlanguages,55configelements,40ConfigurationBasedIssuerNameRegistryclass,86confirmationmethod,147CookieHandler,94CORBA,55crackingatoken,151CreateChannelActingAs,175,176CreateChannelOnBehalfOf,175CreateChannelWithIssuedToken,183CreateToken,93cryptographicoperations,147CSDEFextension,189CSPKGfile,187customizingUIbasedonclaims,37CustomSecurityTokenService,107CustomSecurityTokenServiceConfiguration,108

ASP .NET STS

Page 95: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

243

Ddelegation,176DevFabric,187–213digitalsignaturesfortokens,63dynamicmetadatageneration,205

Eencryptingtokens,63EndRequestevent,75,77end-to-endsecurity,150enforcingauthorizationattheRP,142Esposito,Dino,73externalizingauthentication,16advantages,39

FFederatedAuthentication,40FederatedPassiveSignInStatus,116federationproviders,101relationships,101scenarios,102

federationmetadatadocuments,28FederationPassiveSignIncontrol,81federationproviderroleofIPs,96FederationProviders,99outsourcingfunctions,204

federationrelationships,authenticationflows,101federationscenarios,102FederationUtilityWizard,26creatinganewSTSproject,28NoSTSoption,28UsinganexistingSTS,28

FedUtil.exe,26,39defaultconfiguration,82

Formsauthentication,7,114FormsIdentityobjects,7FP.SeeFederationProvidersFullTrustmode,188

GGenerateNewSTSoption,103genericidentitytransaction,14GenericPrincipal extension,5,7GetOutputClaimsIdentityimplementation,111GetScopemethod,109GetTokenTypeIdentifiersmethod,93

Hholder-of-keyconfirmationmethod,151,153holderofkeytokens,65homeRealm,137HomeRealmDiscovery,136Howard,Michael,4HRD.SeeHomeRealmDiscoveryHTML5,147HttpContext.Current.User,5HttpModulesASP.NET,73ClaimsAuthorizationModule,73SessionAuthenticationModule,72WIFsign-inflow,74WSFederationAuthenticationModule,72

HttpModulespipeline,74

IIClaimsIdentity,18,37,110

Actorproperty,176ClaimTypeproperty,19Issuerproperty,19Subjectproperty,20Valueproperty,19

IClaimsPrincipal,18,37,110identityproviders,12,97allowlistofRPs,98federationproviderrole,96multiple,99multipleSTSendpoints,98roles,96specifying,32standardexample,97unknownRPidentity,99

IIdentity,5IIdentityextensions,18IIS7,84IISauthenticationtypes,6InformationCardFoundationWebsite,133intendedaudienceoftokens,63InternetInformationServicesvs.ASP.NETDevelopmentServer,105

InternetInformationServices(IIS)authentication,6

IP.SeeidentityprovidersIP-FP-RPpattern,126IPrincipal,5extensions,5populating,6

IP-STS,97,106,111

IP-STS

Page 96: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

244

IsInRole,6issuedtokens,64,100Issuemethod,149IssuerNameRegistry,94Issuerproperty,20

JJavaScript,147

KKerberos,97,114constraineddelegation,171–184

Kerberostokens,65keyingstrategies,191

LLeBlanc,David,4lifetimeproperty,122logicalidentitylayer,11logicallayerofidentity,11

Mman-in-the-middleattacks,151MembershipProvider,7MembershipUserNameSecurityTokenHandler,93message-basedsecurity,150end-to-endsecurity,150nonrepudiationappliedtosinglemessages,150properties,150vs.transportsecurity,150

metadata,112dynamicgenerationinthecloud,205generatingdocumentsprogrammatically,112

metadatadocuments,69MicrosoftExcel,148Microsoft.IdentityModel.Claimsnamespace,41Microsoft.IdentityModel.dll,24MicrosoftOutlook,148MicrosoftSilverlight,147MicrosoftVisualStudio,6defaultauthenticationmode,6WindowsAzuretemplates,187–213

MicrosoftWindowsCommunicationFoundation,7

MicrosoftWord,148multipleidentityproviders,96multipleRPapplications,113multitenantapplications,137

Nnamed<microsoft.identityModel/Service>

sections,199NASCARproblem,232networkloadbalanced(NLB)environments,191networkloadbalancing(NLB)–friendlysessions,

125nonrepudiation,150

OOASISIdentityMetasystemInteroperability

TechnicalCommittee,228OAuth2.0protocol,233AuthorizationServerrole,234Clientrole,234implementationforWIF,238profiles,235ProtectedResourcerole,234ResourceServerrole,234WS-Trustintegration,237

OAuthWRAP,204,234OnBehalfOf,174OpenIDimplementinginWIF,232OpenIDmoniker,232OpenIDprovider(OP),232

outsourcingFPfunctions,204

PPage_PreRenderhandler,106passiveclients,56,147HTTPSsecurityoption,150

PassiveRequestorEndpoint,70,72passivesystemsvs.active,146–184pass-throughclaims,134personallyidentifiableinformation,122PFX(PersonalInformationExchange)format,189PII.Seepersonallyidentifiableinformationpolicies,13PostAuthenticateRequestevent,76primitivetokens,65Principal,42processingpipelineinASP.NET,58proofofpossession,153prooftoken,153protocoltransitionSTS,204

RRBAC.SeeRole-BasedAccessSecurity

IsInRole

Page 97: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

245

ReadToken,93redirect-basedprotectionvs.loginpage,80RedirectingToIdentityProviderevent,139relyingparty,12endpointidentity,192load-balancedenvironments,124

RelyingPartyTrust,98remoteservices,148RequestforSecurityTokenResponse(RSTR),149RequestforSecurityToken(RST),149RequestSecurityToken,183RequestSecurityToken.Claimscollection,111RequestSecurityTokenResponse,183Resourcecollection,42REST,55,230restrictingresourcesandactions,33RESTservice,205RESTWebservices,204richclients,148richstacks,147Role-BasedAccessControl,142Role-BasedAccessSecurity,35role-basedauthorization,36RoleDescriptor,70,72roles,35RP.SeerelyingpartyRST.SeeRequestforSecurityTokenRSTR.SeeRequestforSecurityTokenResponseR-STS,111

SSAM.SeeSessionAuthenticationModuleSAML2.0protocol,229–230WIFintegration,229

Saml2SecurityTokenHandler,93Saml2TokenHandler,93Saml11SecurityTokenHandler,93Saml11TokenHandler,93SAMLtokens,66SecureSocketsLayer(SSL)certificates,7securingMicrosoft.NETapplications,3SecurityAssertionMarkupLanguageprotocol,55SecurityTokenCacheKeyclass,191SecurityTokenHandlerclass,93,168securitytokens,13,62authenticationlevelverification,64bearer,65claims,64descriptor,66deserializing,62digitalsignatures,63

duplication,63encryptionanddecryption,63expiration,63format,62,64holderofkey,65integrity,63intendedaudience,63issued,64Kerberos,65primitive,65SAMLformat,64structure,64subelements,66trustedsource,63Username,65validityperiod,63verifying,62WS-*specificationdefinition,64X.509,65

SecurityTokenService,107,108SecurityTokenServiceEndpointelement,72SecurityTokenServiceType,72SecurityTokenVisualizerControlsampleASP.NET

control,68serializinganddeserializingtokens,93SessionAuthenticationModule,72,91sessions,122,191keepingalive,116lifetimeproperty,122networkloadbalancers,124sessiontokens,122singlesign-in,112singlesign-out,115sliding,122state,116sticky,124

SessionSecurityTokenCookieSerializer,191SessionSecurityTokenHandler,93,192SessionSecurityTokens,93,122SharePoint2010,97sign-in,57WF-Federationsequence,58WS-Federationsequence,58

sign-inflowinWIF,74signingin.SeeSingleSign-insigninginacrossmultipleWebsites,230signingout.SeeSingleSign-outSignInRequestMessage,107Silverlight,223

DisplayToken,228makingclaimsavailabletoapplications,227WIFintegration,224

Silverlight

Page 98: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

246

SimpleObjectAccessProtocol(SOAP)Webservices,55

SimpleWebTokens(SWTs),204,236SingleSign-in,113SingleSign-out,115cleanup,117multipleRPs,117oneRP,116WIFSTStemplate,121

slidingsessions,122smartcards,152sqlMembershipProvider,7SSO.SeeSingleSign-onSSOut,115.SeeSingleSign-outstep-upauthentication,140STSactiveendpoints,209addingreferences,32ADFS2.0,103ASP.NETWebsitelinkage,26autogenerated,32availability,102buildingviable,103classesandmethodsinApp_Code,108configurationsettings,108criteriafor"good",102custom,103difficultyofrunning,103generatingatestSTS,28hostedendpoints,103hostinginWindowsAzure,205multipleendpointscenarios,98nonauditing,99off-the-shelfproducts,103performance,102projectstructure,105protocoltransition,204R-STS,106security,102selecting,28separationfromauthenticationmechanism,106template,102usernameandpasswordauthenticationforaWebservice,164

STSauthenticationpage,30STStemplate,102forWCF,158redirectexception,108SingleSign-out,121signingoutcode,117structure,104wsignout1.0,117

subclassing,54Subjectproperty,20subjects,12SunMetro,231SvcTraceViewer.exeutility,203SvcUtil,162SWTs.SeeSimpleWebTokens

TTargetScopes,70Thread.CurrentPrincipal,5Thread.CurrentPrincipal.IsInRole(“Administrators”),

5tokenhandlerclasses,93tokenhandlerscollection,89TokenResolvers,94tokens.See alsosecuritytokensauthenticationlevelverification,64authenticationtokensforservicecalls,180bearer,65bootstrap,172–184certificates,109claims,64deserializing,62destinations,109digitalsignatures,63duplication,63encryptionanddecryption,63,109expiration,63format,62,64holderofkey,65integrity,63intendedaudience,63issuanceprocessparameters,109issuedtokens,64,100Kerberos,65primitive,65processingusingFederationProviders,100proof,153requiredtypevalidation,109SAMLformat,64serializinganddeserializing,93signatures,190size,111structure,64subelements,66trustedsource,63Username,65validityperiod,63verifying,62wellformed,62

Simple Object Access Protocol (SOAP) Web services

Page 99: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

247

tokens(continued)WS-*specificationdefinition,64X.509,65

TokenTypeproperty,93tokenvalidationsettings,89tokenvalidity,62tracelisteners,202transportsecurityvs.message-basedsecurity,150troubleshootingcodeexecutioninthecloud,201TrustChannel,238trustedIPs,63trustedsubsystems,170TurboTax,148Twitter,148

Uusernameandpasswordauthenticationscenario

usingWIFwithinWCF,167Usernametokens,65users.Seesubjects

VValidateRequestmethod,109ValidateToken,93validityperiodoftokens,63valueconstantsandClaimtypes,131Valueproperty,19verifyingsecuritytokens,62

Wwaparameter,59,61wauthparameter,61wauthparameterinWS-Federation,140WCF,145–184claims,162client-sidefeatures,170–184configuration,156,161configuringaservicetouseWIF,168cookiemode,196delegation,175–184findingclaiminformation,169RESTservice,205similiaritieswithASP.NET,146–184testingservicestool,159usernameandpasswordauthenticationwithWIF,164

WCFsecuritymodelvs.WIFmodel,167WIFSTStemplate,158

WCFroleinWindowsAzure,195–203

WCFServicetemplate,154WcfTestClient.exe,159wctparameter,60,61wctxparameter,61Webapplications,147Webauthenticationprotocols,232Webbrowsersign-in,57web.configfile,6,53,82,155WebIdentities,230Webprotocolsvs.WS-*,231

WebResourceAuthorizationProtocol,234WebRole.csfile,191Webroles,190WebserversASP.NETDevelopmentServer,105IISvs.VisualStudiobuilt-inWebserver,105

Webservices,146–184invoking,149securitypolicies,149

Webservicesinaload-balancedenvironment,196

Websiteauthentication,57whrparameter,61whrparameterinWS-Federation,136WIF.See alsoWindowsIdentityFoundationASP.NETMVCframework,216–223authenticationmethods,141<authorization>elements,37classes,90client-sidefeatureswithWCF,170–184configelements,40configuration,82delegation,175–184extending,216HttpModules,72IsInRoleintegration,36mainclasses,82OAuth2.0,238processingpipelineinASP.NET,58runtimeassemblies,188SAMLprotocolortokenformat,69servingevents,53sign-inflow,74signoutimplementation,117subclassing,54supportedprotocols,57usingtheSDKtools,53Webbrowsersign-in,57Websiteauthentication,57

WIFRuntime,24–47installing,24

WIF Runtime

Page 100: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

248

WIFSDK,24differencesbetweenversions,25installing,25

WIFSDKSTStemplate.SeeSTStemplateWIFsign-inflow

AuthenticateRequestevent,75AuthorizeRequestevent,75EndRequestevent,75PostAuthenticateRequestevent,75

WIFSoftwareDevelopmentKit.SeeWIFSDKWIFSTStemplate,102WIFSTSTemplateforWCF,158

WIF-WCFpipelineintegration,168Windowsauthentication,6WindowsAzure,185–213AppFabricAccessControlService(ACS),204CSPKGfile,187–213DevFabric,187–213,192diagnostics,201environments,192FullTrustmode,188globalassemblycache(GAC),188hostinganSTS,205localsimulationenvironment,187–213ProductionEnvironment,192Roles,188sessions,191sessionsinaload-balancedenvironment,196StagingEnvironment,192tracelisteners,202tracing,201VisualStudiotemplates,187–213WCFrole,195Webrole,190WIFandpassivefederation,191WIFRuntimeAssembly,188X.509certificates,188

WindowsCardSpace,228WindowsCommunicationFoundation,52,

145–184integrationwithWIF,52

WindowsIdentityFoundationcompatibilitywith.NETFramework,24–47definition,15fourmainuses,52integrationwithASP.NETorWindowsCommunicationFoundation,52

IsInRoleintegration,36purpose,16WIFRuntime,24–47WIFSDK,24WS-Federationimplementation,72

WindowsPresentationFoundation,14extension,5

WindowsServerroles,15WRAP.SeeWebResourceAuthorizationProtocolwreplyparameter,61wresultparameter,60,61WriteToken,93WritingSecureCode,4WS-*,55vs.SAML-P,57vs.Webprotocols,231

WS-*capableclients,56WSFAM,72WSFAMevents,90WS-Federation,55,56audienceverification,193implementationinWIF,72metadatadocumentcompatibility,70parameters,59sign-insequence,58SingleSign-outprocess,119waparameter,59,61wauthparameter,61wctparameter,60,61wctxparameter,61whrparameter,61,136wreplyparameter,61wresultparameter,60,61wtrealmparameter,59,61

WS-Federation1.2specification,56WSFederationAuthenticationModule,72WS-<function>,55wsignin1.0,61wsignout1.0,61,117WS-Security,148signingandencryptingmechanisms,150

WS-Trust,148flowanduseofkeys,152intergratingwithOAuth2.0,237invokingWebservices,149

WSTrustChannel,180WSTrustServiceContractclass,159wtrealm,110wtrealmparameter,59,61

XX.509certificate,7,65,152,188tokens,65

X509CertificateValidatorclass,89X509SecurityTokenHandler,93XAPfiles,225

WIF SDK

Page 101: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

Vittorio BertocciVittorioBertocciisaSeniorArchitectEvangelistinDeveloperandPlatformEvangelism(DPE)andakeymemberoftheextendedengineeringteamthatproducesMicrosoft’sclaims-basedplatformcomponents(forexample,WindowsIdentityFoundationandADFS2.0).Heisresponsibleforidentityevangelismforthe.NETdevelopercommunityanddroveinitiativessuchastheIdentityDeveloperTrainingKit(http://go.microsoft.com/fwlink/?LinkId=148795)andtheIdElementshow(http://channel9.msdn.com/shows/identity/ )onChannel9.

VittorioholdsamasterdegreeinComputerScience,andhebeganhiscareerdoingresearchoncomputationalgeometryandscientificvisualization.In2001,heJoinedMicrosoftItaly,whereheimmediatelyfocusedonthe.NET

platformandthenascentfieldofWebservicessecurity,becomingareferenceatthenationalandEuropeanlevel.

In2005,VittoriomovedtoRedmond,wherehehelpedtolaunchthe.NETFramework3.5byworkingwithFortune100andGlobal100companiesoncutting-edgeSOAprojectsbasedonWCF,WF,andCardSpace.Hebecamemoreandmorefocusedonidentitythemes,eventuallyundertakinghiscurrentmissionofevangelizingclaims-basedidentityintomainstreamuse.

Inthelastfiveyears,thismissionhasledhimtospeakaboutidentityin23countriesand4continents.VittorioisaregularspeakeratconferencessuchasMicrosoftPDC,TechEdUSA,TechEdEurope,TechEdAustralia,TechEdNewZealand,TechEdJapan,TechDaysBelux,GartnerSummit,EuropeanIdentityConference,IDWorld,OreDev,NDC,IASA,Bastaandmanyothers.

Vittorioisapublishedauthor,bothintheacademicandindustryworlds,andhaswrittenmanyarticlesandpapers.Heisco-authorofA Guide to Claims-Based Identity and Access Control(MicrosoftPress,2010)andUnderstanding Windows CardSpace(Addison-Wesley,2008).Heisaprominentauthority/bloggeronidentity,WindowsAzure,.NETdevelopment,andrelatedtopics,andheshareshisthoughtsatwww.CloudIdentity.net.

Vittoriolivesinthelush,greencityofRedmondwithhiswife,Iwona.Hedoesn’tmindthegrayskiestoomuch,buteverytimehehashalfachancehefliestosomebeachplace,beitHawaiiorCamogli,hishometowninItaly.

Page 102: Programming Windows Identity eBook - …ptgmedia.pearsoncmg.com/images/9780735627185/samplepages/...to become the Architect for the Identity and Access team tasked with building a

Stay in touch!TosubscribetotheMicrosoft Press® Book Connection Newsletter—fornewsonupcomingbooks,events,andspecialoffers—pleasevisit:

What do you think of this book?Wewanttohearfromyou!Toparticipateinabriefonlinesurvey,pleasevisit:

Tellushowwellthisbookmeetsyourneeds—whatworkseffectively,andwhatwecandobetter.Yourfeedbackwillhelpuscontinuallyimproveourbooksandlearningresourcesforyou.

Thankyouinadvanceforyourinput!

microsoft.com/learning/booksurvey

microsoft.com/learning/books/newsletter