Tải bản đầy đủ (.pdf) (272 trang)

programming windows identity foundation

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.97 MB, 272 trang )

www.it-ebooks.info
Programming
Windows
®
Identity
Foundation
Vittorio Bertocci
www.it-ebooks.info
PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, 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
Microsoft and the trademarks listed at />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 Ryan


Developmental Editor: Devon Musgrave
Project Editor: Rosemary Caperton
Editorial 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
www.it-ebooks.info
To Iwona, moja kochanie
www.it-ebooks.info
www.it-ebooks.info
  v
Contents at a Glance
Part I WindowsIdentityFoundationforEverybody
 1 Claims-Based Identity                                     3
 2
Core ASPNET Programming                               23
Part II WindowsIdentityFoundationforIdentity
Developers
 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
www.it-ebooks.info
www.it-ebooks.info
  vii
Table of Contents
Foreword                                                           xi
Acknowledgments                                                  xiii
Introduction                                                       xvii

Part I WindowsIdentityFoundationforEverybody
 1 Claims-Based Identity                                     3
What Is Claims-Based Identity?                                       3
Traditional Approaches to Authentication                         4
Decoupling Applications from the Mechanics of
Identity and Access                                            8
WIF Programming Model                                           15
An API for Claims-Based Identity                                16
WIF’s Essential Behavior                                        16
IClaimsIdentity and IClaimsPrincipal                             18
Summary                                                         21
 2 Core ASPNET Programming                               23
Externalizing Authentication                                        24
WIF Basic Anatomy: What You Get Out of the Box                24
Our First Example: Outsourcing Web Site Authentication
to an STS                                                     25
Authorization and Customization                                    33
ASPNET Roles and Authorization Compatibility                   36
Claims and Customization                                      37
A First Look at <microsoftidentityModel>                        39
Basic 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!
www.it-ebooks.info
viii Table of Contents
Part II WindowsIdentityFoundationforIdentity
Developers

 3 WIF Processing Pipeline in ASPNET                        51
Using Windows Identity Foundation                                 52
WS-Federation: Protocol, Tokens, Metadata                           54
WS-Federation                                               55
The Web Browser Sign-in Flow                                  57
A Closer Look to Security Tokens                                62
Metadata Documents                                         69
How WIF Implements WS-Federation                                 72
The WIF Sign-in Flow                                          74
WIF Conguration and Main Classes                                 82
A Second Look at <microsoftidentityModel>                     82
Notable Classes                                               90
Summary                                                         94
 4 Advanced ASPNET Programming                          95
More About Externalizing Authentication                             96
Identity Providers                                             97
Federation Providers                                          99
The WIF STS Template                                        102
Single Sign-on, Single Sign-out, and Sessions                         112
Single Sign-on                                               113
Single Sign-out                                              115
More About Sessions                                         122
Federation                                                       126
Transforming Claims                                         129
Pass-Through Claims                                         134
Modifying Claims and Injecting New Claims                     135
Home Realm Discovery                                       135
Step-up Authentication, Multiple Credential Types,
and Similar Scenarios                                         140
www.it-ebooks.info

Table of Contents ix
Claims Processing at the RP                                        141
Authorization                                               142
Authentication and Claims Processing                          142
Summary                                                        143
 5 WIF and WCF                                          145
The Basics                                                        146
Passive vs Active                                            146
Canonical Scenario                                           154
Custom TokenHandlers                                       163
Object Model and Activation                                  167
Client-Side Features                                               170
Delegation and Trusted Subsystems                            170
Taking Control of Token Requests                              179
Summary                                                        184
 6 WIF and Windows Azure                                 185
The Basics                                                        186
Packages and Cong Files                                     187
The WIF Runtime Assembly and Windows Azure                 188
Windows Azure and X509 Certicates                          188
Web Roles                                                       190
Sessions                                                    191
Endpoint Identity and Trust Management                       192
WCF Roles                                                       195
Service Metadata                                            195
Sessions                                                    196
Tracing and Diagnostics                                       201
WIF and ACS                                                     204
Custom STS in the Cloud                                           205
Dynamic Metadata Generation                                205

RP Management                                             213
Summary                                                        213
www.it-ebooks.info
x Table of Contents
 7 The Road Ahead                                        215
New Scenarios and Technologies                                    215
ASPNET MVC                                                216
Silverlight                                                   223
SAML Protocol                                               229
Web 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!
www.it-ebooks.info
  xi
Foreword
Afewyearsago,Iwassittingatatableplayingagameofpokerwithafewcolleaguesfrom
MicrosoftwhohadallbeeninvolvedatvarioustimesinthedevelopmentofWebServices
EnhancementsforMicrosoft.NET(WSE).DonBox,MarkFussell,KirillGavrylyuk,andIplayed
thehandswhileshowmanextraordinaireDougPurdyengageduswithlivelybanterand
morethanafewquestionsabouttheproduct—allofthisinfrontofthecamerasatthe
MSDNstudios.
Wehadeachselectedapersonfromtheeldtoplayfor;someonewhomweeach
thoughthadmadeasignicantcontributiontothesuccessofWSEbuthadn’tbeenadirect
memberoftheproductteamitself.Ifwewon,thenournomineewouldgetaprize,atoken
ofourappreciationfortheworkthatheorshehaddone.Myselectionwasaguycalled
VittorioBertocciwhowasworkingforMicrosoftinItalyatthetime.I’dnevermetVittorio,

norevenseenaphotoofhim,buthewasaprolicposteronourinternaldiscussionlist,
clearlyunderstoodthekeysecurityconceptsfortheproductincludingtheWS-*protocols,
andhadevencraftedanextensiontoenableReliableMessagingdespitesomeofthecrude
extensibilitywehadinplaceatthetime.Vittoriowassomeoneworthplayingforbut,
unfortunately,Ididn’twin.
Timepassed,theWindowsCommunicationFoundation(WCF)supersededWSE,andImoved
tobecometheArchitectfortheIdentityandAccessteamtaskedwithbuildingaSecurity
TokenServiceforWindowsServer.Oneday,outoftheblue,Igotane-mailfromVittorio
tosaythathe’dmovedtoRedmondtotakeonaPlatformEvangelistroleandaskingifwe
couldmeetup.OfcourseIsaidyes,butwhatIcouldn’thaveanticipatedwasthatmaneof
jet-blackhair
Vittoriowasdeeplyinterestedintheworkthatweweredoingtoenableaclaims-based
programmingmodelfor.NET,ontopofwhichweplannedtobuildthesecondversionofour
securitytokenservice.Overtime,theseideasbecamethe“Geneva”waveofproductsand
werenallybirthedastheWindowsIdentityFoundationandActiveDirectoryFederation
Services2.0.
Throughoutseveralyearsofproductdevelopment,Vittoriobecamenotonlyaremarkable
spokespersonfortheproductsbutakeysourceoffeedbackonourwork,bothfromthe
customersandpartnersthathemetwithandfromhisowndirecteffortstousetheproduct.
Hewasinstrumentalinencouragingme,andtheproductteam,totakeonthelast-minute
taskofmakingWIFruninWindowsAzurejustintimeforPDC2009andtheproductrelease.
WatchingVittoriopresentasessiononWIFisapleasure—hisdepthofknowledgeandhis
creativepresentationskillsallowhimtodeliverthemessageonanincreasinglyimportant
topicdespitethefactthatitistoofrequentlytaintedwiththedrynessofthe“security”label.
www.it-ebooks.info
xii Foreword
Withinthepagesofthisbook,you’lllearnhowtousetheWindowsIdentityFoundationfrom
someonewhoisnotonlyagreatteacherbutisalsodeeplyfamiliarwiththeconceptsbe-
hindthetechnologyitselfandwhohasworkeddirectlywiththeproductteam,andmyself
personally,onaveryclosebasisoverthecourseofthelastfourtoveyears.

Vittoriotakesyouthroughtheterminologyandkeyconcepts,andexplainstheintegration
ofWIFwithASP.NET,WindowsCommunicationFoundation,andWindowsAzure,culminat-
inginaspeculativelookaheadatthescenariosthattheproductmighttackleinafuture
release.Iencourageyou,thereader,tothinkdeeplyabouttheconceptshereandhowyou
willmanageidentityintheapplicationsthatyougoontobuild;it’satopicthatisbecoming
increasinglyimportanttobothenterprisesandtheWebcommunity.
Finally,IwanttothankVittorioforhisenthusiasm,support,andtirelessenergyoverthe
years.Ihavebutonenalrequestofhim:pleasegetahaircut.
Hervey Wilson
Architect, AppFabric Access Control Service
Microsoft, Redmond
July 2010
www.it-ebooks.info
  xiii
Acknowledgments
You create the world of the dream. We bring the subject into that dream and ll it
with their subconscious.
—Cobb in “Inception”, Christopher Nolan, 2010
Sometimeago,afriendaskedmewhatthepointwasofwritingabookwhenIalreadyhave
awell-readblog.Therearemanyexcellentanswerstothatquestion,fromtheextrareach
thatabookhastotheadvantagesofreadingwithouthavingtoconstantlyghttheop-
portunitycostsofnotfollowingalink.Myfavoriteanswer,however,isthatwhereasablogis
aone-manoperation,abookistheresultofthecontributionofmanypeopleanditsvalue
forthereaderisproportionallyhigher.Itmightbemynameonthecover,butthereality
isthatIstandontheshouldersofmanynepeople,whoIwanttoacknowledgehere.I’ve
beenworkingwithidentityforthelast8yearsorso,interactingwithanincredibleamountof
people;hence,IamprettysureI’llforgetsomebody.Iapologizeinadvance.
PeterKronisaPrincipalSoftwareDeveloperEngineerontheWIFteam,andtheofcial
technicaleditorofthisbook.Withouthispatience,thoroughness,anddeepknowledgeof
WIF,thiswouldhavebeenamuchinferiorbook.

HerveyWilsonistheArchitectoftheAccessControlservice.HeledtheWebServices
Enhancements(WSE)team,andhehappenstobetheonewhoenvisionedWindowsIdentity
Foundation.I’vebeenworkingwithHerveysince2002,wellbeforeImovedtoRedmond.At
thetime,IwasstillusinghisWSEforsecuringsolutionsforItaliancustomers.Ifyoubelieve
whatMalcomGladwellsaysinhisbookOutliers: The Story of Success(Little,BrownandCo.,
2008),thatyouneed10,000hoursofpracticeforbecomingrealgoodatsomething,nobody
contributedmorethanHerveytomyprofessionalgrowthintheeldofIdentity.Iamvery
honoredheagreedtowritetheforewordforthisbook.Thanks,man!
ThecrewatMicrosoftPresshasbeenoutstanding,choppingintomanageablechunksmy
long“Itanglish”sentenceswithoutchangingthemeaningandworkingaroundmyabysmal
delaysandcrazyschedule.(Inthelastyearalone,Ihandedaboardingpasstosmilingladies
55times.)Specically,thanksgotoBenRyanandGerryO’Brienforhavingtrustinmeand
thebook,toDevonMusgraveforbootstrappingtheproject,andtoRosemaryCaperton
forrunningtheproject.SteveSagmanofWaypointPressledafantasticproductionteam:
RogerLeBlancasCopyEditor,ThomasSpeechesasProofreader,andAudreyMarras
Illustrator.SpecialthankstoAudreyforworkingonreallychallengingillustrations:youcan
pullouttheneedlesfrommydollnow!
StuartKwan,GroupProgramManagerforWIF,andConradBayer,GMfortheIdentityand
Accessdivision,havebeengreatpartnersandsupportedthisprojectfromtheverystart.
www.it-ebooks.info
xiv Acknowledgments
Ididmostofthewritingatnight,onweekends,andduringvacationtime,butattimes
thebookdidimpactmydayjob.JamesConardandNeilHutson,SeniorDirectorsinthe
DeveloperandPlatformEvangelismgroupandmydirectmanagementchain,havebeenvery
patientandsupportiveoftheeffort.
JustineSmithandBrjannBrekkan,fromtheBusinessGroupoftheIdentityandAccess
Division,havebeenincrediblyhelpfulonactivitiesthatultimatelyhadanimpactonthe
samplecodediscussedhere.
ToddWest,atthetimewiththeWIFtestteam,isoneofthemostgiftedWebservices
developersI’veevermet.MostoftheguidanceregardingWIFandWindowsAzureinthis

bookandoutthereistheresultofhiswork.
MygoodfriendCalebBaker,ProgramManagerontheWIFteam,isanever-endingsource
ofinsightsandusefuldiscussions.HeisalsotheowneroftheWIFandSilverlightintegration.
TheSilverlightcodesamplesareallbasedonhiswork.
TogetherwithHervey,theoriginalWSEteammergedwithWIFtoo.Ihadachanceto
taptheirbrainscountlesstimes.ThankstoSiddShenoy,GovindRamanathan,Vick
Mukherjee,HongMeiGe,andKeithBallinger.
TheentireWIFteamcontributedtothisbook.HereI’llcallafewpeopleouttogiveyou
afeelingforthequalityoftheirwork.DanielWuwasofgreathelponsessions;Brent
SchmaltzwaskeyforhelpingmeunderstandtheinnerworkingsofWIFandWCF;VaniNori
andVickdevisedthewayofusingWIFwithMVC;JunaidTisekarwaskeyforstartingthe
workwithWIFandOAuth2.0;ShiungYongwasinstrumentalinguringoutsomepartsof
theWIFpipelineintheearlydaysofWIF.
Manyothersintheidentityproductteamcontributedthroughtheyears:thankstoJan
Alexander,VijayGajjala,ArunNanda,MarcGoodner,MikeJones,CraigWittenberg,
DonSchmidt,RuchiBhargava,SeshaMani,MattSteele,andSamDevasahayam.
MyteammatesintheWindowsAzureplatformevangelismteamplayedakeyrolein
keepingmeonmytoes,andthey’resimplyawesometohangoutwith.ThankstoRyan
Dunn,DavidAiken,NigelWatling,andZachOwen.Pleasedeleteallthepicturesyou
saved!
TheguysatSouthworks,thecompanythathelpedmewithpracticallyalltheidentity
samplesandlabsinthelasttwoyears,arefantastictoworkwith.ManythankstoMatias
Woloski,PabloDamiani,TimOsborn,JohnnyHalife,andmanyothers.
ConversationsaboutidentitywithGianpaoloCarraroandEugenioPacewereextremely
valuable,especiallytheonesrelatedtotheP&Pguideonclaims-basedidentityledby
Eugenio.
www.it-ebooks.info
Acknowledgments xv
DonovanFollettehasbeentheADFSevangelistforalongtime,sharingwithmethepains
andthejoysoftheclaims-basedidentityrenaissanceatPDC08.Evenifnowheisallcozy

inhisnewOfcerole,Icannotforgethisincrediblecontributiontobringingidentitytothe
community.
Ofcourse,wewouldnotbeevendiscussingthisifKimCameronhadnotdriventhe
conversationontheidentitymetasystemandclaims-basedidentitywiththeentireindustry.
Thankyou,Kim!
Mywife,IwonaBialynicka-Birula,deservesspecialthanks.Sheacceptedandsupported
thiscrazyinitiativenomatterwhat,whetheritmeantskippingbeachtimewhileinMauior
copingwithinsuranceagentsandcontractorsafterourhousegotooded.Withouther,
notonlywouldyounotbeholdingthisbookinyourhands,Idon’tknowwhatIwoulddo….
Thankyou,darling.Ipromise:nomorebooksforsometime!
Finally,Iwanttothankyou:thereadersofmyblog,whofollowedfaithfullymyramblingsfor
sevenyearswithoutaskingtoooftenabouttheweirdblogname;theparticipantsoftheWIF
workshopsinBelgium,UK,Germany,Singapore,Melbourne,andRedmond,whoputupso
nicelywithmy“sexy”accent;andtheattendeesofthemanysessionsIgaveateventsallover
theworldinthelastveyears.Withoutyourquestions,yourcritiques,yourcomments,your
compliments,andyourlongingforunderstanding,Iwouldhaveneverfoundthemotivation
todothisandtheotherthingsIdoforevangelizingidentity.Thisbookisforyou.
www.it-ebooks.info
  xvii
Introduction
IthasbeensaidthateveryprobleminComputerSciencecanbesolvedbyaddingalevelof
indirection.
Youdon’thavetogofartondexamplesofsuccessfulapplicationsofthatprinciple.Before
theintroductionoftheconceptofdriver,programshadtoberewritteneverytimeone
changedsomethingassimpleasthemonitor.BeforetheintroductionofTCP/IP,programs
targetingatokenringnetworkenvironmenthadtoberewrittenifthenetworkprotocol
changed.DriversandTCP/IPhelpedtofreeapplicationdevelopersfromtheneedtoworry
aboutunnecessarydetails,presentingthemwithagenericfaçadewhileleavingthenitty-
grittydetailstotheunderlyinginfrastructure.Inadditiontomakingthedeveloperprofession
ahappierone,theapproachledtomorerobustandlong-livedsoftwareforthebenetof

everybody.
Forvarioushistoricalreasons,authenticationandidentitymanagementpracticesneverreally
followedthesamerouteofmonitorsandnetworkcards.Adding“authentication”toyour
softwaretodaystilllargelymeansmessingwiththecodeoftheapplicationitself,writing
logicthattakescareindetailoflowleveltaskssuchasverifyingusernameandpasswords
againstanaccountstore,jugglingwithX509certicatesorsimilar.Whenyouaresparedfrom
handlingthingsatsuchlowlevel,whichusuallymeansthatyoutookastrongdependencyon
yourinfrastructureandyourapplicationwillbeunmovablewithoutsubstantialrewriting:just
likeaprogramfromthepre-driversera.
Asyouwilllearnintherstchaptersofthisbook,claims-basedidentityischangingallthis.
Withoutgoingtoomuchintodetails,claimsarethemeanstoaddthatextralevelof
indirectionthateludedtheidentityworldsofar.Theintroductionofopenprotocolsenjoying
wideindustryconsensus&support,theconvergetowardtheideaofameta-systemfor
identity,thesuccessofmetadataformatswhichcanautomatemanytediousanderror-prone
taskscreatedtheperfectstormthatgeneratedthepracticescollectivelyknownasclaims-
basedidentity.Claimsarepavingthewayforidentityandaccessmanagementtobepushed
outsideofapplicationsanddownintheinfrastructure,freeingdevelopersfromtheneed
tohandleitexplicitlywhileenhancingsolutionswithwelcomeextraadvantages(suchas
cross-platforminteroperabilityoutofthebox).
Ihavespentfullfouryearsworkingalmostexclusivelyonclaims-basedarchitectureswith
customersandproductteamshereinRedmond;themodelissound,anditinvariablydelivers
signicantimprovementsagainstanyotherauthenticationsystem.However,untilrecently,
actuallyimplementingsystemsaccordingtothemodelwasapainfulexperience,sinceit
requiredwritinglargeamountsofcustomcodethatwouldhandleprotocols,cryptography,
andsimilarlowlevelaspects.
www.it-ebooks.info
xviii Introduction
Thisallchangedwhen,inOctober2008,Microsoftannouncedthe“Geneva”waveof
claims-awarebetaproducts:amongthosetherewasWindowsIdentityFoundation,the
protagonistofthebookyouareholding,whichwasnallyreleasedinNovember2009.

WindowsIdentityFoundation(WIF)isMicrosoft’sstackforclaims-basedidentity
programming.Itisanewfoundationaltechnologywhichhelps.NETdeveloperstotake
advantageoftheclaimsbasedapproachforhandingauthentication,authorization,custom-
izationandingeneralanyidentity-relatedtaskwithouttheneedtowriteanylow-levelcode.
Truetotheclaims-basedidentitypromise,youcandecidetouseWIFtoexternalizeall
identityandaccesscontrollogicfromyourapplications:VisualStudiowillmakeitabreeze,
andyouwillnotberequiredtoknowanydetailabouttheunderlyingsecurityprotocols.If
youwanttotakenercontroloftheauthenticationandauthorizationprocess,however,WIF
offersyouapowerfulandexibleprogrammingmodelthatwillgiveyoucompleteaccessto
allaspectsoftheidentitymanagementpipeline.
ThisbookwillshowyouhowtouseWindowsIdentityFoundationforhandling
authentication,authorizationandidentity-drivencustomizationofyour.NETapplications.
Althoughthetextwilloftenbetask-oriented,especiallyforthenovicepartofthebook,the
ultimategoalwillalwaysbetohelpyouunderstandingtheclaimsbasedapproachandthe
patternthatismostappropriatefortheproblemathand.
WhoIsThisBookFor?
PartIofthebookisfortheASP.NETdeveloperwhowantstotakeadvantageofclaims-based
identitywithouthavingtobecomeasecurityexpert.Althoughtherearenorequirements
aboutpre-existingsecurityknowledge,youdoneedtohavehands-onASP.NETprogram-
mingknowledgetoprocientlyreadPartI.
InPartIIIshiftgearprettydramatically,assumingthatyouareanexperienced.NET
developerwhoknowsaboutASP.NETpipeline,Formsauthentication,X.509certicates,LINQ
syntaxandthelike.Ioftentrytoaddsidebarswhichintroducethetopicifyouknowlittle
aboutitbutyouwanttofollowthetextanyway,butrealityisthatwithoutconcrete,hands-
onknowledgeofthe.NETFramework(andspecicallyC#)PartIIcouldbehardtonavigate.I
alsoassumethatyouaremotivatedtoinvestenergyonunderstandingthe“why”sofidentity
andsecurity.
Identityisanenablingtechnology,whichisneverfoundinisolationbutalwaysasa
componentandenhancementofothertechnologiesandscenarios.Thisbookdiscusses
howtoapplyWIFwithavarietyoftechnologiesandproducts,andofcoursecannotafford

providingintroductionsforeverything:inordertobeabletoapplytheguidanceinthe
variouschaptersyou’llneedtobeprocientinthecorrespondingtechnology.Thegood
newsisthatthechaptersarereasonablydecoupledfromeachother,sothatyoudon’tneed
www.it-ebooks.info
Introduction xix
tobeaWCFexpertforappreciatingthechaptersaboutASP.NET.Chapter3andChapter4
requireyoutobefamiliarwithASP.NETanditsextensibilitymodel.Chapter5isforexperi-
encedWCFdevelopers.Chapter6requiresyoutobefamiliarwithWindowsAzureandits
programmingmodel.Chapter7sweepsonanumberofdifferenttechnologies,including
SilverlightandASP.NETMVCFramework,andexpectsyoutobeateasewithterminology
andusage.
Thebottomlineisthatinordertofullytakeadvantageofthebookyouneedtobeanexpert
.NETandWebdeveloper.Ontheotherhand,thebookcontainsalotofarchitecturalpatterns
andexplanationswhichcouldeasilybeappliedtoproductsonotherplatforms:henceifyou
areanarchitectthatcanstomachpatternsexplanationsintertwinedwithcodecommentary,
chancesarethatyou’llndthisbookagoodreferenceonhowclaims-basedidentitysolves
variouscanonicalproblemsintheidentityandaccessspace.
SystemRequirements
You’llneedthefollowingsoftwareandhardwaretobuildandrunthecodesamplesfor
thisbook:

 Microsoft®Windows7;WindowsServer2003ServicePack2;WindowsServer2008R2;
WindowsServer2008ServicePack2;WindowsVista

 WindowsIdentityFoundation1.0runtime

 WindowsIdentityFoundationSDK4.0

 Microsoft®InternetInformationServices(IIS)7.5,7.0or6.0


 Microsoft®.NETFramework4.0

 VisualStudio2010

 1.6-GHzPentiumorcompatibleprocessor

 1GBRAMforx86

 2GBRAMforx64

 Anadditional512MBRAMifrunninginavirtualmachine

 DirectX9–capablevideocardthatrunsat1024×768orhigherdisplayresolution

 5400-RPMharddrive(with3GBofavailableharddiskspace)

 DVD-ROMdrive

 Microsoftmouseorcompatiblepointingdevice

 Approximately78MBofavailableharddiskspacetoinstallthecodesamples
www.it-ebooks.info
xx Introduction
NotethattheWIFruntimeandtheWIFSDK3.5arecompatiblewithVisualStudio2008and
the.NETFramework3.5SP2.TheMarch2010versionoftheIdentityTrainingKitcontains
mostofthesamplesofthebookinaformthatiscompatiblewithVS2008andthe.NET
Framework3.5,howeverpleasenotethatthecodeinthetextreferstoVS2010andthereare
smalldifferenceshereandthere.
CodeSamples
Thecodesamplesforthisbookareavailablefordownloadhere:

/>Clickthedownloadlinkandfollowtheinstructionstosavethecodesamplestoyourlocal
harddrive.
ThecodesamplesusedinthisbookaremostlyfromtheIdentityDeveloperTrainingKit,a
collectionofhands-onlabs,presentations,andinstructionalvideos,whichismeanttohelp
developerslearnMicrosoft’sidentitytechnologies.Itisaself-extracting.EXE.Everylabhasits
ownsetup,whichwilltakecareofmostprerequisitesforyou.Pleasefollowtheinstructions
ontheWelcomepage.
ProducingtheIdentityDeveloperTrainingKitisoneofthethingsIdoduringmydayjob.
WhereasinthebookIhighlightcodesnippetstohelpyouunderstandthetechnology,in
theIdentityDeveloperTrainingKitdocumentationIgivestep-by-stepinstructions.Feel
freetocombinethetwoapproachesasyourampupyourknowledgeofWindowsIdentity
Foundation.
TheIdentityDeveloperTrainingKitisalivingdeliverable;everytimethereisanewver-
sionofaproductIupdateitaccordingly.However,Iwanttomakesurethatthecode
samplesreferencedinthebookwillnotbreak.Forthatreason,Iamincludinginthebook
codesamplearchivethecurrentversionofthetrainingkit,June2010,whichwillalwaysbe
available,evenifIkeepupdatingthetrainingkitinitsoriginaldownloadlocation.
ErrataandBookSupport
We’vemadeeveryefforttoensuretheaccuracyofthisbookanditscompanioncontent.If
youdondanerror,pleasereportitonourMicrosoftPresssiteatOreilly.com.
 1. Goto.
 2. IntheSearchbox,enterthebook’sISBNortitle.
 3. Selectyourbookfromthesearchresults.
 4. Onyourbook’scatalogpage,underthecoverimage,you’llseealistoflinks.
 5. ClickView/SubmitErrata.
www.it-ebooks.info
Introduction xxi
You’llndadditionalinformationandservicesforyourbookonitscatalogpage.Ifyouneed
additionalsupport,pleasee-mailMicrosoftPressBookSupportat
PleasenotethatproductsupportforMicrosoftsoftwareisnotofferedthroughtheaddresses

above.
WeWanttoHearfromYou
AtMicrosoftPress,yoursatisfactionisourtoppriority,andyourfeedbackourmostvaluable
asset.Pleasetelluswhatyouthinkofthisbookat:
/>Thesurveyisshort,andwereadeveryoneofyourcommentsandideas.Thanksinadvance
foryourinput!
StayinTouch
Let’skeeptheconversationgoing!We’reonTwitter: />www.it-ebooks.info
www.it-ebooks.info
Programming Windows Identity Foundation
  1
PartI
Windows Identity Foundation
for Everybody
In this part:
Claims-Based Identity                                                   3
Core ASPNET Programming                                             23
Claims-basedidentitypromotesseparationofconcernsatalevelneverachievedbefore
intheidentitymanagementworld.Asaresult,implementationssuchasWindowsIdentity
Foundation(WIF)canprovidetoolingthatwillenabledeveloperstoaddauthenticationca-
pabilitiestotheirapplicationswithouttheneedtobecomesecurityexperts.
Thetwochaptersinthispartofthebookdeliveronthatpromise:theycontainindications
thatcanbeunderstoodandappliedbyanyASP.NETdeveloper,regardlessofhowmuchthe
developeralreadyknowsaboutsecurity.Ifyouarenotasecurityguru,andyoudon’twantto
becomeone,WindowsIdentityFoundationallowsyoutotacklethemostcommonauthen-
ticationandauthorizationchallengeswithoutenteringintothegorydetailsofcredentials
andprotocolmechanics.ItissosimplethatideallyyoucouldevenskipmostofChapter1,
“Claims-BasedIdentity,”andgostraighttothe“WIFProgrammingModel”section.Youwould
stillbeabletouseWIFforsecuringyourapplicationsinthesimplestcase,althoughhaving
thebackgroundweprovideinChapter1wouldhelpyoutodosomoreeffectively.

Ifyouareinterestedintakingnercontroloftheidentityandaccessmanagementprocess,
PartII,“WindowsIdentityFoundationforIdentityDevelopers,”isforyou.However,Isuggest
thatyoustillglancethroughPartI,asitscharacterizationofclaims-basedidentitywillbe
requiredknowledgeinPartII.
www.it-ebooks.info
www.it-ebooks.info
  3
Chapter1
Claims-Based Identity
In this chapter:
What Is Claims-Based Identity?                                           3
WIF Programming Model                                               15
Summary                                                             21
MicrosoftWindowsIdentityFoundation(WIF)enablesyoutoapplytheprinciplesof
claims-basedidentitywhensecuringyourMicrosoft.NETapplication.Claims-basedidentity
issoimportantthatIwanttomakesureyouunderstanditwellbeforeIformallyintroduce
WindowsIdentityFoundation.
Claims-basedidentityisanaturalwayofdealingwithidentityandaccesscontrol.However,
theoldwaysofdoingthisarewellestablished,sobeforedelvingintothenewapproach,it’s
usefultodescribeandchallengetheclassicassumptionsaboutauthenticationandauthoriza-
tion.Onceyouhaveaclearunderstandingofsomeoftheissueswithtraditionalapproaches,
I’llintroducethebasicprinciplesofclaims-basedidentity—I’llsayenoughtoenableyouto
procientlyuseWindowsIdentityFoundationforthemostcommonscenarios.Thischapter
containssomesimplicationsthatwillgetyougoingwithoutoverloadingyouwithinfor-
mation.Foramorethoroughcoverageofthesubject,refertoPartII,“WindowsIdentity
FoundationforIdentityDevelopers.”
Finally,we’lltakeourinitiallookathowWIFimplementsthemechanismsofclaims-based
identityandhowyou,thedeveloper,canaccessthemainelementsexposedbyitsobject
model.
Afterreadingthischapter,you’llbeabletodescribehowclaims-basedidentityworksand

howtotakeadvantageofitinsolutionstocommonproblems.Furthermore,you’llbeableto
deneWindowsIdentityFoundationandrecognizeitsmainelements.
WhatIsClaims-BasedIdentity?
Note Ifyoualreadyknowaboutclaims,feelfreetoskipaheadtothe“WIFProgramming
Model”section.Ifyouareinabighurry,Iofferyouthefollowingsummaryofthissectionbefore
youskiptothenextsection:Claims-basedidentityallowsyoutooutsourceidentityandaccess
managementtoexternalentities.
www.it-ebooks.info

×