|
|
|
|
|
|
|
Technologies:
Active Directory,Visual C# .NET
|
|
Total downloads :
|
|
|
Total page views :
|
57604
|
|
Rating :
|
|
5/5
|
|
This article has been rated :
|
3 times
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
Related EbooksTop Videos
|
|
|
Description
|
|
LINQ for Visual C# 2005 is a short yet comprehensive guide to the major features of LINQ. It thoroughly covers LINQ to Objects, LINQ to SQL, LINQ to DataSet, and LINQ to XML.
|
|
|
|
|
|
|
|
|
|
|
|
|
Configure the Web Application for Forms Authentication:
a) IIS Configuration:
In Virtual Directories properties
- Click the Directory Security tab, and then click the Edit button in the Anonymous access group.
- 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
- 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>
-
Modify <authorization> element as following.
<authorization> <deny users="?" /> <allow users="*" /> </authorization>
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
- Create a FormsAuthenticationTicket that contains the userdata (UserData can contain roles for the user).
- Encrypt the ticket.
- Create a new cookie / session that contain the encrypted ticket.
- Add the cookie / session to the list of cookies / sessions returned to the user's browser.
- 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
|
|
|
|
|
|
|
|
|
|
|
|
Rohit Kshirsagar
Rohit Kshirsagar is Project Engineer in Wipro Technologies Ltd.
|
|
|
|
|
|
|
|
|
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.
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|