The .NET Developer's Guide to Directory Services ProgrammingBy Joe Kaplan, Ryan Dunn .... Microsoft MVPs Joe Kaplan and Ryan Dunn have written a practical introduction to programming dir
Trang 1The NET Developer's Guide to Directory Services Programming
By Joe Kaplan, Ryan Dunn
Publisher: Addison Wesley Professional Pub Date: May 08, 2006
Print ISBN-10: 0-321-35017-0 Print ISBN-13: 978-0-321-35017-6 Pages: 512
The NET Developer's Guide to Directory Services Programming will come as a
welcome aid.
Microsoft MVPs Joe Kaplan and Ryan Dunn have written a practical introduction to
programming directory services, using both versions 1.1 and 2.0 of the NET Framework The extensive examples in the book are in C#; a companion Web site includes both C# and Visual Basic source code and examples.
Readers will
Learn to create, rename, update, and delete objects in Active Directory and ADAM Learn to bind to and search directories effectively and efficiently
Learn to read and write attributes of all types in the directory
Learn to use directory services within ASP.NET applications
Get concrete examples of common programming tasks such as managing Active Directory and ADAM users and groups, and performing authentication
Experienced NET developersthose building enterprise applications or simply interested in
learning about directory serviceswill find that The NET Developer's Guide to Directory
Services Programming unravels the complexities and helps them to avoid the common
pitfalls that developers face.
Trang 2The NET Developer's Guide to Directory Services Programming
By Joe Kaplan, Ryan Dunn
Publisher: Addison Wesley Professional Pub Date: May 08, 2006
Print ISBN-10: 0-321-35017-0 Print ISBN-13: 978-0-321-35017-6 Pages: 512
Trang 6Index
Trang 7Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and the publisher wasaware of a trademark claim, the designations have been printedwith initial capital letters or in all capitals
The NET logo is either a registered trademark or trademark ofMicrosoft Corporation in the United States and/or other
countries and is used under license from Microsoft
The authors and publisher have taken care in the preparation ofthis book, but make no expressed or implied warranty of anykind and assume no responsibility for errors or omissions Noliability is assumed for incidental or consequential damages inconnection with or arising out of the use of the information orprograms contained herein
The publisher offers excellent discounts on this book when
ordered in quantity for bulk purchases or special sales, whichmay include electronic versions and/or custom covers and
content particular to your business, training goals, marketingfocus, and branding interests For more information, please
Trang 9To the developers that struggle so hard each day with integrating Active Directory and ADAM meaningfully into their applications Remember: "This is not 'Nam, this is
software development; there are rules."
R.D
Trang 10Titles in the Series
Brad Abrams, NET Framework Standard Library Annotated
Reference Volume 1: Base Class Library and Extended Numerics Library, 0-321-15489-4
Brad Abrams and Tamara Abrams, NET Framework Standard
Library Annotated Reference, Volume 2: Networking Library, Reflection Library, and XML Library, 0-321-19445-4
Trang 165.7:
Using an Attribute Scope Query to Retrieve Data from the Members of a Group 179
Trang 189.1:
The DirectoryContext and DirectoryContextType Public Members 326
Trang 22TABLE Security Descriptor Read Behavior 227
Trang 24application
Knowing the tremendous value of having a great technical book
by my side, I tried something crazy I posted an entry on myblog[1] suggesting that if any subject matter experts were
interested in putting such a book together, I'd be happy to help
by reviewing their work and introducing them to the editors atAddison-Wesley Apparently, that post rekindled a latent interest
in the minds of a bunch of Microsoft MVPs, who just needed alittle push to get going Joe Kaplan and Ryan Dunn threw
themselves on the grenade and now here I sit, writing this
foreword!
[1] http://pluralsight.com/blogs/keith/archive/2004/10/15/2831.aspx
In the meantime, I have been fortunate to be able to reviewmuch of this book, and I've learned a great deal about
programming System.DirectoryServices by reading the draft
chapters Chapter 3 was invaluable when I was building the
identity-aware application I mentioned earlier, and overall thebook provided a number of insights that I share with studentswhen I teach my security course at Pluralsight If you are
currently doing (or even considering) any work with
Trang 25be glad you did
Directories surround us, but many enterprise programmers
aren't aware of the wealth of information on their own domaincontrollers For example, it would be wise to avoid building yourown "Users" table in SQL Server if you can simply leverage userdata in Active Directory It would be utter folly to create a
password database and roll your own authentication protocol on
an intranet where you could simply leverage Kerberos One neattechnique I learned from this book was how to use "SID
binding" to look up a user's record in Active Directory once
you've authenticated that user These are the sorts of practicaltechniques used every day by directory programming experts,but you'd be hard-pressed to find them by simply reading thedocumentation
I've seen a lot of books written by professional technical
writers For some of them, you can tell that the only leg up theauthor has over your own experience is that he read the
documentation a few weeks before you did This is not one ofthose books Joe and Ryan together have answered literally
thousands of questions in public forums such as the ADSI
USENET newsgroup at microsoft.public.adsi.general They knowthe pain points that you'll encounter when you program againstActive Directory, and this book overflows with practical wisdom
Trang 26We wrote this book with the vision that it would be the
definitive guide for helping developers leverage directory
services from Active Directory and Active Directory/ApplicationMode (ADAM) in their NET applications Even though version1.0 of the NET Framework shipped in 2001 with a namespacecalled System.DirectoryServices (SDS) for doing this kind of work,the resources available to developers using these technologieshave lagged behind This is the book that we fervently wished
we had back when we were first developing software for ActiveDirectory It was an idea that took a little while to come to
fruition: Perhaps a bit of our back story will help to frame ourperspective
Ryan was working at a very large professional services firm thatwas selling off its consulting services capabilities As part of theseparation, a new IT infrastructure needed to be created It fell
to Ryan to figure out how to automate HR data feeds to
provision Active Directory accounts and how to manage all of itwith only a skeleton crew and a few custom apps This was inthe NET version 1.0 beta 2 timeframe and NET seemed
promising
Separately, but in an eerily similar vein, Joe was working in the
IT organization of a large professional services firm that wascontemplating a massive email system migration from a populargroupware platform to Microsoft's Exchange 2000 Server
Exchange works on top of Active Directory, and Joe was asked
to help out on the integration project between Active Directoryand the groupware system's directory
Both projects required a heavy dose of directory services magic
to tie the systems together and migrate from the competingplatforms The applications were not simple scripts, but
Trang 27
Protocol (LDAP) code work correctly in ASP.NET? What were all
of those flags used for? How do we make these objects behavethe way we expect? How do we extend the schema to
accommodate our own custom business logic?
Naturally, we went to the web-based message boards and
newsgroups seeking advice, but found very little Some peoplehad some of the answers if we translated their logic from scripts
or C++ programs, but more people were asking than
answering With hard work and sometimes-fortuitous chance,
we eventually pieced it together, but it was far more difficultthan it needed to be
Flash forward to 2006: The NET Framework has matured
significantly, with a milestone 2.0 release, and so has the NETdevelopment community Books and resources abound for justabout every topic you could imagine However, directory
We stuck around the message boards, and over the last severalyears, we worked actively in the online development community
to help developers of all stripes solve their directory servicesdevelopment problems We know from our work in the
community that there tends to be a lot of confusion on how best
to leverage what became of Active Directory Service Interfaces(ADSI) in the new managed model of System.DirectoryServices
We took the most common problems that developers wrestle
Trang 28services programming will be much more effective than before
Our approach for this book tends to be very pragmatic We
focus heavily on code samples showing how to do things theright way, sometimes at the expense of brevity However, we donot hesitate to dig under the covers and provide answers forhow things really work We start with the basic skills that everydirectory services developer should understand and build a solidfoundation We then layer on more advanced topics and
scenarios that we have run into firsthand and that we know
from our work in the community that developers still strugglewith When we are done, you should have all the tools needed
to tackle the advanced scenarios and build the types of
applications you need
Outside of this book, we endeavor to support our readers bymaking examples, errata, additional topics, and tools available
on our companion web site, www.directoryprogramming.net
What Is Covered?
The book primarily focuses on programming LDAP with the
additions to NET, System.DirectoryServices.ActiveDirectory (SDS.AD)
developers who may never use older versions, it is useful tolearn the newer features by understanding the previous
shortcomings
Trang 29of ADAM as well While we do not provide specific examples oftargeting non-Microsoft directories, we do try to point out theissues that are most likely to affect you, and how to avoid
them
The book is divided into two parts Part I (Chapters 19) is allabout the fundamentals of LDAP programming It introduces thekey concepts and provides a solid foundation upon which to
build any type of directory services application Part II
(Chapters 1012) is about applying the fundamentals from Part I
to real-world problems and provides more of a "cookbook"
approach The topics in these last chapters come from what wesee developers wrestling with everyday and our own
experiences as we struggled to learn this
Chapter 1 introduces the basic concepts of LDAP and discussesthe key directory services that the book focuses on, Active
Directory and ADAM In Chapter 2, we continue the introductionwith a survey of the APIs available for programming LDAP usingthe NET Framework and discuss how they relate to each other
Starting with Chapters 3 and 4, we cover the basic mechanics
of accessing Active Directory or ADAM In Chapter 3, we focus
in detail on connecting to the directory, as well as creating,
moving, renaming, and deleting objects Chapter 4 covers thebasics of searching Searching is the fundamental activity ofLDAP programming, so a solid grounding is essential
Chapter 5 continues with the searching theme, but goes intodetail on the advanced topics The 2.0 release of the NET
Framework has added a host of new searching features, so wecover all of these here and provide complete samples
Chapter 6 focuses on the intricacies of reading and writing
attributes in the directory We discuss all of the different
attribute syntaxes, including the ones that tend to give
Trang 30Chapter 7 covers LDAP schema and extensions, explaining keypoints that the enterprise developer should know for designingnew schema
We delve into the Windows security model in Chapter 8,
addressing not only LDAP security and how it integrates withWindows security, but also the challenges of the security
context in the ASP.NET environment We will show you how touse Kerberos delegation and teach you common issues to lookfor We also cover access control lists (ACLs) in Active Directoryand ADAM and discuss the code access security (CAS) model inthe NET Framework, as well as how it applies to directory
samples, as well as real answers to common problems Chapter
11 covers group management in detail We conclude in Chapter
12 with a variety of different approaches for authentication withLDAP, including a discussion of the alternatives
We also include three appendices Appendix A shows some
different approaches for doing COM interop in NET COM
interop is often required when working with these technologies,
so it is useful to know the options here Appendix B providesour list of "must-have" tools for LDAP programmers working
Trang 31book that deal with those problems If you are stuck and need
an answer fast, Appendix C might help you to use the book
more effectively We also tell you how to get in touch with us ifyou can't find what you are looking for here
Target Audience
This book was written with the NET enterprise application
developer in mind While it is generally applicable to any NETdeveloper doing directory services programming, we have
included many topics of specific interest to the enterprise
audience, including performance, scalability, and security
scenarios If you are new to NET or programming in general,this may not be the book for you We assume an overall
moderate level of comfort and do not explain basic
programming techniques
The samples in the book are primarily in C#, but we do not
specifically target C# developers The samples try to focus onthe usage of the classes themselves and not on the specific
programming language In cases where there are substantialdifferences beyond curly braces and semicolons, we show VisualBasic NET samples as well Additionally, all of the book's
samples are available in both C# and Visual Basic NET on thebook's web site
Trang 32For ASP.NET examples, Windows 2000 Server, WindowsServer 2003, or Windows XP running IIS is required
Visual Studio NET (either the 2005 or the 2003 version) ishelpful, but not required
Trang 33From Joe Kaplan
They always say that writing a book is a lot of work, but onlythose who have done so can truly understand what that means
First of all, thanks to our technical reviewers: Carlos, Matt,
Weiqing, Richa, Smitha, Joe R., Keith, Dominick, and Joe S Youimproved the quality of this material immensely If anything isstill wrong, it is not your fault
Thanks to Ryan, who initially jumped on Keith's request for
someone to write this book and kindly asked me to help Webarely knew each other when this started, but I now consideryou a friend
Thanks to Keith Brown, not only for introducing us to his
publisher, but for reviewing as well After reading your articlesand seeing you speak for years, it has been a privilege to workwith you directly
The Active Directory team at Microsoft not only creates theseAPIs and products, but also actually listens to suggestions abouthow to make them better Thanks especially to Dmitri Gavrilovand Eric Fleischman for their limitless knowledge and
willingness to share it
Thanks to everyone at Addison-Wesley for making this happen.You put a lot of faith in two new authors and demonstrated
incredible patience along the way as we struggled mightily withour deadlines Joan Murray and Jessica D'Amico kept us on thepath and actually managed to wring a book out of us after all.Julie Nahil got our raw material turned into a finished productand the intrepid Audrey Doyle painstakingly proofed every
Trang 34Johnson figured out how to get this thing in front of you
Thanks especially to my wife, Karen, and son, Evan, for theirpatience, love, and support Evan, I'm not sure if you will
remember this when you are older, but I'm sure Mommy willnever be old enough to forget this
Finally, thanks to the directory services community at large,MVPs and random strangers alike, for being on the front linesevery day and bringing a never-ending stream of real-worldproblems to the table This would not have been possible
without you
From Ryan Dunn
Writing this book has taken a lot of time and effort over the lastyear It was not accomplished in a vacuum and both Joe and Ihave a lot of appreciation for the people who really made thishappen In no particular order, I would like to acknowledge andthank the following people
Keith Brown, for helping us get started and providing somuch support Born of a possibly frustrated request to have
a book on System.DirectoryServices, this book probably wouldnot have happened if he didn't ask
Joan Murray, Jessica D'Amico, Karen Gettman, Audrey
Doyle, Julie Nahil, and everyone at Addison-Wesley for
time authors Joan and Jessica were marvelous to work with
being so extraordinarily helpful and patient with two first-as they guided us through this process
Our reviewers (Carlos, Dominick, Joe R., Weiqinq, Keith,Matt, Smitha, Richa, and Joe S.) for checking our facts (in
Trang 35Joe, for being a great coauthor, conference companion, andfriend We met for the first time in Chicago over lunch todiscuss how we would write this beast A little over a yearlater, it is finally done Suffice it to say, it just would not bethe same book without Joe's knowledge baked in here aswell
My wife, Shailaja, who supported me constantly and nevercomplained when book time cut into our time I love you
Trang 36
Joe Kaplan works in Accenture's internal IT organization,
building enterprise applications using the NET Framework Hespecializes in directory services programming, for which he hasbeen recognized as a Microsoft MVP An industry veteran of
more than thirteen years, he also thrives on working with thedevelopment community and solving real-world problems
Ryan Dunn of Avanade is a NET developer and architect with
experience in a wide range of industries and technologies Hehas consulted on a number of projects to integrate clients'
applications with Active Directory and ADAM Ryan is a MicrosoftMVP for ASP.NET, though he currently focuses primarily on
directory services Ryan can be reached on the Web in the
ASP.NET forums or through his blog at http://dunnry.com/blog
Trang 38
Active Directory
This chapter describes the fundamental underpinnings of thematerial in the rest of the book Since this book is essentiallyabout programming directory services using the LightweightDirectory Access Protocol (LDAP) with Microsoft's NET platform,
we introduce the basic concepts of LDAP directories and
protocols here
The first part of the chapter introduces directory services andsome specific directory technologies The second part is moretechnical and delves into some of the details concerning theLDAP specification itself
Trang 39Anyone who has ever used a phone book or library card catalogrealizes that directories are very useful tools For software
developers, having a single place to store enterprise-wide userdata such as email addresses and passwords is equally as
useful Essentially, a directory service is simply an electronicrolodex of sorts
Our experience with the Internet shows us that having simple,standardized protocols is one of the keys to broad adoption of atechnology Try imagining the Internet today if there were nostandard DNS system to resolve names into numeric IP
addresses or an HTTP protocol to deliver web content! However,
as is often the case in this industry, it took a while for a
standard protocol (LDAP) to emerge and later become the
underpinnings to one of the most successful data repositoriestoday
Directory services within organizations started out as point
solutions to particular problems As developers of these
systems began to realize that many of the systems they worked
on needed the same set of services, open products and toolsbegan to emerge in the marketplace However, these productstended to use proprietary network protocols, programmatic
interfaces, and metaphors for organizing and naming the
content they stored At a certain point, people realized that astandard for directory services would allow huge interoperabilitywithin industry, government, and academia, saving everyoneenormous amounts of time and money Thus, the X.500
standard was born
X.500 was adopted in 1988 under the ITU-T RecommendationX.500 (also known as ISO/IEC 9594: Information Technology-Open Systems Interconnection-The Directory) It formalizedmany important concepts that are essential to directory services
Trang 40in the directory, a naming standard for referring to objects inthe directory, and standard protocols for clients accessing thedirectory and other directories interacting with the directory
One essential part of X.500 is the Directory Access Protocol, orDAP DAP defines a client/server protocol for accessing an X.500directory using the application layer of the Open System
Interconnection (OSI) model The OSI model was originally
adopted because the implementers of the standard were
interested in using X.500 to manage email addresses for theOSI message-handling application known as X.400
Unfortunately, the OSI model is somewhat complex to
implement and many thought an easier standard would be moreuseful for most clients The University of Michigan had the idea
of developing to the existing protocol and binding it directly tothe TCP/IP network protocol for use over the Internet They
called their implementation Lightweight Directory Access
Protocol, or LDAP