Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Active Directory C# » 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.

Page Views : 84353
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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
}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
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 | Modify 
Code? by Robin On March 2, 2007
The article is great! Can you supply the complete code?
Reply | Email | 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 | 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 | Modify 
ADAuthentication by Mallika On June 15, 2011
Article is very helpful.Can you please send me the source code? Thanks!
Reply | Email | Modify 
Re: ADAuthentication by Binary On January 18, 2012
Article is very helpful! Can you please send me the source code? binary.x64 #at# gmail #dot# com Thanks!
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.