Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Active Directory » Forms Authentication with Active Directory

Forms Authentication with Active Directory

This article and sample code explains how you can take advantage of Active Directory in Web applications for authenticate and authorize the Web site users.

Technologies: Active Directory,Visual C# .NET
Total downloads :
Total page views :  57606
Rating :
 5/5
This article has been rated :  3 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor



Configure the Web Application for Forms Authentication:

a) IIS Configuration:

In Virtual Directories properties

  1. Click the Directory Security tab, and then click the Edit button in the Anonymous access group.
  2. Select the Anonymous access check box and click on Edit button and clear the Allow IIS to control password check box. Because the default anonymous account IUSR_MACHINE does not have permission to access Active Directory, create a new least privileged account and enter the account details in the Authentication Methods dialog box.

b) Modifications in Web.Config:

In Web.config in the <authentication> element and change the mode attribute to Forms

  1. 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.

    <authentication mode="Forms">
    <
    forms loginUrl="logon.aspx" name="adAuthName" timeout="60" path="/"> </forms>
    </
    authentication>

  2. Modify <authorization> element as following.

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

  3. Add <Identity> element and set it's impersonate value to true.

    <Identity impersonate = "true" />

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

1. Develop a component having a method AuthenticateUser which will check / validate the supplied credentials (Username, Password, and Domain Name) against an AD (Active Directory). 

public bool AuthenticateUser(string domain, string username, string password)
{
string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry( LDAPPATH, domainAndUsername, password);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if(null == result)
{
return false;
}
// Update the new path to the user in the directory
LDAPPATH = result.Path;
}
catch (Exception ex)
{
throw new Exception("Error authenticating user." + ex.Message);
}
return true;
}

2. Add GetRoles method which will retrieve roles for the User if you want to set authorization for accessing methods as per user role.

Web Page For Authenticating The User And Creating Forms Authentication Ticket

Develop webpage say login page which will authenticate user by calling IsAuthenticated method of the component.

On successful authentication

  1. Create a FormsAuthenticationTicket that contains the userdata (UserData can contain roles for the user).
  2. Encrypt the ticket.
  3. Create a new cookie / session that contain the encrypted ticket.
  4. Add the cookie / session to the list of cookies / sessions returned to the user's browser.
  5. Redirect User to the original page what he requested.

The sample code is as given:

string adPath = LDAP://LDAPServer/DC=doamin,DC=com;
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if(true == adAuth.AuthenticateUser(txtDomainName.Text, txtUserName.Text, txtPassword.Text))
{
Response.Write("Autheticated");
String role = (adAuth.GetRoles(txtDomainName.Text, txtUserName.Text, txtPassword.Text));
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(60), false,userdata );
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie( FormsAuthentication.FormsCookieName , encryptedTicket);
Response.Cookies.Add(authCookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUserName.Text,false));
}
else
{
lblError.Text = "Authentication Failed please check UserName & Password";
}
}
catch(Exception ex)
{
Response.Write("Error authenticating. " + ex.Message);
}

Implement an Authentication Request Handler to Construct a GenericPrincipal Object

Implements the Application_AuthenticateRequest event handler within global.asax and creates a GenericPrincipal object for the currently authenticated user. This will contain roles for that user, retrieved either from the FormsAuthenticationTicket contained in the authentication cookie / session or in the event itself by calling GetRoles method of component. Then associate the GenericPrincipal object with the current HttpContext object that is created for each Web request (since the event is fired for each request).

GenericIdentity id=new GenericIdentity(authTicket.Name, "Authentication");
GenericPrincipal principal = new GenericPrincipal(id, roles);

Using Permissions for Authorizing Methods Access

Now since we have added roles to Principal object we can give access to execute method / events according to the roles. We can secure our method / events depending on the roles. This can be done programmatically by checking HttpContext.Current.User.IsInRole() method or by adding Permission Attribute before the methods / events.

The example is as shown below:

//Programmatically
Public void Create()
{
if(HttpContext.Current.User.IsInRole() == "Create")
{
//Statements to create
}
else
{
Response.write("You are not authorized to Create.");
}
}
// Permission Attribute
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Create")]
Public void Create()
{
//Statements to create
}


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Rohit Kshirsagar
Rohit Kshirsagar is Project Engineer in Wipro Technologies Ltd.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
COde file by aKoranteng On February 28, 2007
Hi Rohit, Can you email me a zipped file for this file. I can't find it here.
Reply | Email | Delete | Modify | 
Code? by Robin On March 2, 2007
The article is great! Can you supply the complete code?
Reply | Email | Delete | Modify | 
Code is mssing by Ranger On June 26, 2007
This is a great article. Is there any place we can download the code?
Reply | Email | Delete | Modify | 
Require code by Jebamalai On March 8, 2008
Hi. The article is too Good, This is what I too want. Can you email me the code. My email ID is : jayachitra@angleritech.com
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved