Click here to Skip to main content
15,881,812 members
Articles / Web Development / ASP.NET
Article

Forms Authentication with Active Directory in ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
2.55/5 (15 votes)
30 Nov 2006CPOL7 min read 103.4K   2.2K   38   20
This Article describes authentication with windows active directory in ASP.NET 2.0. This is very useful to the programmers those who writing an intranet site while they can authenticate users with the domain users of their server.

Introduction

ASP.NET Forms authentication allows users to identify themselves by entering credentials (a user name and password) into a Web Form. Upon receipt of these credentials, the Web application can authenticate the user by checking the user name and password combination against a data source.

This part describes how to authenticate users against the Microsoft Active Directory directory service by using the Lightweight Directory Access Protocol (LDAP).

Active Directory

Typically Active Directory is managed using the graphical Microsoft Management Console. Active Directory is an implementation of LDAP directory services by Microsoft for use in Windows environments. Active Directory allows administrators to assign enterprise-wide policies, deploy programs to many computers, and apply critical updates to an entire organization. An Active Directory stores information and settings relating to an organization in a central, organized, accessible database. Active Directory networks can vary from a small installation with a few hundred objects, to a large installation with millions of objects.

Active Directory is a directory service used to store information about the network resources across a domain. An Active Directory (AD) structure is a hierarchical framework of objects. The objects fall into three broad categories — resources (e.g. printers), services (e.g. e-mail), and users (accounts, or users and groups). The AD provides information on the objects, organizes the objects, controls access, and sets security.

Naming

AD supports UNC (\), URL (/), and LDAP URL names for object access. AD internally uses the LDAP version of the X.500 naming structure. Every object has a Distinguished name (DN), so a printer object called HPLaser3 in the OU Marketing and the domain foo.org, would have the DN: CN=HPLaser3, OU=Marketing, DC=foo, DC=org where CN is common name and DC is domain object class, DNs can have many more than four parts. The object can also have a Canonical name, essentially the DN in reverse, without identifiers, and using slashes: foo.org/Marketing/HPLaser3. To identify the object within its container the Relative distinguished name (RDN) is used: CN=HPLaser3. Each object also has a Globally Unique Identifier (GUID), a unique and unchanging 128-bit string which is used by AD for search and replication. Certain objects also have a User principal name (UPN), an objectname@domain name form.

Lightweight Directory Access Protocol

In computer networking, the Lightweight Directory Access Protocol, or LDAP ("ell-dap"), is a networking protocol for querying and modifying directory services running over TCP/IP.

A client starts an LDAP session by connecting to an LDAP server, by default on TCP port 389. The client then sends operation requests to the server, and the server sends responses in turn. With some exceptions the client need not wait for a response before sending the next request, and the server may send the responses in any order.

The basic operations are, in order:

  • Bind - authenticate and specify LDAP protocol version
  • Start TLS - protect the connection with Transport Layer Security (TLS), to have a more secure connection
  • Search - search for and/or retrieve directory entries
  • Compare - test if a named entry contains a given attribute value
  • Add a new entry
  • Delete an entry
  • Modify an entry
  • Modify DN - move or rename an entry
  • Abandon - abort a previous request
  • Extended Operation - generic operation used to define other operations
  • Unbind - close the connection (not the inverse of Bind)

Directory structure

The protocol accesses LDAP directories, which follow the X.500 model:

A directory is a tree of directory entries.

An entry consists of a set of attributes.

An attribute has a name (an attribute type or attribute description) and one or more values.

The attributes are defined in a schema (see below).

Each entry has a unique identifier: its Distinguished Name (DN). This consists of its Relative Distinguished Name (RDN) constructed from some attribute(s) in the entry, followed by the parent entry's DN. Think of the DN as a full filename and the RDN as a relative filename in a folder.

Be aware that a DN may change over the lifetime of the entry, for instance, when entries are moved within a tree. To reliably and unambiguously identify entries, a UUID may be provided in the set of the entry's operational attributes.

An entry can look like this when represented in LDIF format (LDAP itself is a binary protocol):

dn: cn=John Doe,dc=example,dc=com

cn: John Doe

givenName: John

sn: Doe

telephoneNumber: +1 555 6789

telephoneNumber: +1 555 1234

mail: john@example.com

manager: cn=Barbara Doe,dc=example,dc=com

objectClass: inetOrgPerson

objectClass: organizationalPerson

objectClass: person

objectClass: top

dn is the name of the entry; it's not an attribute nor part of the entry. "cn=John Doe" is the entry's RDN, and "dc=example,dc=com" is the DN of the parent entry. The other lines show the attributes in the entry. Attribute names are typically mnemonic strings, like "cn" for common name, "dc" for domain component, and "mail" for e-mail address.

A server holds a subtree starting from a specific entry, e.g. "dc=example,dc=com" and its children. Servers may also hold references to other servers, so an attempt to access "ou=Some department,dc=example,dc=com" could return a referral or continuation reference to a server which holds that part of the directory tree. The client can then contact the other server. Some servers also support chaining, which means the server contacts the other server and returns the results to the client.

LDAP rarely defines any ordering: The server may return the values in an attribute, the attributes in an entry, and the entries found by a search operation in any order.

How to Use Forms Authentication with Active Directory in ASP.NET 2.0

Step 1. Create a Web Application with a Logon Page

This procedure creates a simple C# Web application that contains a logon page that allows a user to enter a user name and password and a default page that displays the identity name and group membership information associated with the current Web request.

To create a Web application with a logon page Start Microsoft Visual Studio® .NET and create a new C# ASP.NET Web Application named AuthenticationAD. Add a new assembly reference to System.DirectoryServices.dll. This provides access to the System.DirectoryServices namespace that contains managed types to help with Active Directory querying and manipulation.

Add the controls listed in Table 1 to Default.aspx to create a simple logon form.

Table 1.

Text Box - txtUser

Text Box - txtPass

Button - sbtLogin

Label - lblError

Set the TextMode property of txtPass to Password.

In Solution Explorer, right-click AuthenticationAD, point to Add, and then click Add Web Form.

In the Name field, type default1.aspx, and then click Open.

In Solution Explorer, right-click default1.aspx, and then click Set As Start Page.

Double-click default1.aspx to display the page load event handler. Add a Label in this page and set Text property of Label as ‘Secure Page’.

Step 2. Configure the Web Application for Forms Authentication

This procedure edits the application's Web.config file to configure the application for Forms authentication.

To configure the Web application for forms authentication

Use Solution Explorer to open Web.config.

Locate the <authentication> element and change the mode attribute to Forms.

Add the following <forms> element as a child of the authentication element and set the loginUrl, name, timeout, and path attributes as shown in the following.

<BR><authentication mode="Forms"><BR><BR><forms loginUrl="Default.aspx" name="adAuthCookie" timeout="60" path="/"><BR><BR></forms><BR><BR></authentication>

Add the following <authorization> element beneath the <authentication> element. This will allow only authenticated users to access the application. The previously establish loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Default.aspx page.

XML
<authorization> <BR><BR><deny users="?" /><BR><BR><allow users="*" /><BR><BR></authorization><BR>

Add the following <appSettings> code. In the place of domainName.com, add your network domain name and instead of serverIP add your server Name.

XML
<BR><appSettings><BR><BR><add key="DomainName" value="domainName.com"/><BR><BR><add key="serverpath" value="serverIP"/><BR><BR></appSettings><BR>

Save Web.config.

Step 3. Develop LDAP Authentication Code to Look Up the User in Active Directory

To develop LDAP authentication code to look up the user in Active Directory Right click on the design view of Default.aspx and add the following IsAuthenticated method in AuthenticationAD.aspx.vb that accepts a domain name, user name and password as parameters and returns Boolean to indicate whether or not the user with a matching password exists within Active Directory. The method initially attempts to bind to Active Directory using the supplied credentials. If this is successful, it returns True otherwise False.

VB.NET
Public Function <BR>IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean<BR><BR>Dim _path As String<BR><BR>Dim _filterAttribute As String<BR><BR>Dim servername As String = ConfigurationSettings.AppSettings("serverpath").ToString<BR><BR>'Whether Authenticated User or Not <BR><BR>Dim domainAndUsername As String = domain + "\" + username<BR><BR>Dim entry As New DirectoryEntry("LDAP://" + servername, domainAndUsername, pwd)<BR><BR>Try<BR><BR>Dim obj As Object = entry.NativeObject<BR><BR>Dim search As New DirectorySearcher(entry)<BR><BR>search.Filter = "(SAMAccountName=" + username + ")"<BR><BR>search.PropertiesToLoad.Add("cn")<BR><BR>Dim result As SearchResult = search.FindOne<BR><BR>If result Is Nothing Then<BR><BR>Return False<BR><BR>End If<BR><BR>_path = result.Path<BR><BR>_filterAttribute = CType(result.Properties("cn")(0), String)<BR><BR>Catch ex As Exception<BR><BR>Return False<BR><BR>End Try<BR><BR>Return True<BR><BR>End Function<BR><BR>Add a reference to the System.DirectoryServices.dll assembly.<BR><BR>Add the following using statements to the top of AuthenticationAD.aspx.vb. <BR><BR>Imports System.DirectoryServices<BR><BR>Imports System.Configuration<BR><BR>Imports System.Web.Security<BR><BR>Double Click on the sbtLogin button and in its Click event write the following code<BR><BR>Dim domainName As String = ConfigurationSettings.AppSettings("DomainName").ToString()<BR><BR>If (IsAuthenticated(domainName, txtUser.Text.Trim, txtPass.Text.Trim) = True) Then<BR><BR>Session("User") = txtUser.Text.Trim<BR><BR>Response.Redirect("SecurePage.aspx ", False)<BR><BR>Else<BR><BR>lblError.Visible = True<BR><BR>lblError.Text = "Your login attempt was not successful. Please try again."<BR><BR>End If<BR>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Aamer Alduais23-Jun-12 19:13
Aamer Alduais23-Jun-12 19:13 
Rant[My vote of 1] good job copying and pasting from the Microsoft patterns & practices article.. Pin
degree45120029-Dec-09 2:49
degree45120029-Dec-09 2:49 
GeneralNeed help. didn't go to Securepage after enter user name and password. Pin
sonny196927-Jul-09 8:42
sonny196927-Jul-09 8:42 
QuestionAuthenticate Using Display Name and Password? Pin
jp2code19-May-09 4:15
professionaljp2code19-May-09 4:15 
GeneralWell done Pin
mikeg213-Mar-09 11:16
mikeg213-Mar-09 11:16 
GeneralGreat Article, Thanks Pin
mokingham21-May-08 16:11
mokingham21-May-08 16:11 
QuestionAlmost working... Pin
Jason Hollenberg15-Nov-07 11:45
Jason Hollenberg15-Nov-07 11:45 
GeneralFYI: KB Article Pin
MikeEast10-Jan-07 22:35
MikeEast10-Jan-07 22:35 
GeneralRe: FYI: KB Article Pin
louis31528-Mar-08 10:20
louis31528-Mar-08 10:20 
QuestionWindows authentication? Pin
Not Active1-Dec-06 2:33
mentorNot Active1-Dec-06 2:33 
AnswerRe: Windows authentication? Pin
Snijeesh1-Dec-06 19:50
Snijeesh1-Dec-06 19:50 
GeneralRe: Windows authentication? Pin
Not Active2-Dec-06 2:44
mentorNot Active2-Dec-06 2:44 
AnswerRe: Windows authentication? Pin
jeremy.wiebe5-Dec-06 3:33
jeremy.wiebe5-Dec-06 3:33 
GeneralRe: Windows authentication? Pin
Abi Bellamkonda4-Dec-06 12:29
Abi Bellamkonda4-Dec-06 12:29 
AnswerRe: Windows authentication? Pin
L Hills4-Dec-06 23:47
L Hills4-Dec-06 23:47 
GeneralGood Pin
Pravesh Soni1-Dec-06 2:19
Pravesh Soni1-Dec-06 2:19 
GeneralSame thing Pin
Leonardo Pessoa30-Nov-06 23:11
Leonardo Pessoa30-Nov-06 23:11 
GeneralWhoops Pin
NormDroid30-Nov-06 20:55
professionalNormDroid30-Nov-06 20:55 
Looks like you're not following CP Submission guidelines.


We made the buttons on the screen look so good you'll want to lick them. Steve Jobs

GeneralRe: Whoops Pin
Snijeesh30-Nov-06 21:40
Snijeesh30-Nov-06 21:40 
GeneralRe: Whoops Pin
NormDroid30-Nov-06 21:46
professionalNormDroid30-Nov-06 21:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.