85443

Custom login mechanism for a ASP.NET website

Question:

I'm working on a ASP.NET website and I need to get away with some custom but simple login mechanism. I started from the famous <a href="http://eisk.codeplex.com/" rel="nofollow">Employee Info Starter Kit</a>

Here's what I have so far:

<strong>On a ASP.NET page:</strong>

protected void ButtonLogOn_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtUserName.Value) || String.IsNullOrEmpty(txtPassword.Value)) labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("You can login using a username and a password associated with your account. Make sure that it is typed correctly."); else { //if the log-in is successful LoginPage LoginBack = new LoginPage(); if (LoginBack.VerifyCredentials(txtUserName.Value, txtPassword.Value) == 0) { SiteLogin.PerformAuthentication(txtUserName.Value, checkBoxRemember.Checked); } else { labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("<strong>Login Failed!</strong><hr/>The username and/or password you entered do not belong to any User account on our system.<br/>You can login using a username and a password associated with your account. Make sure that it is typed correctly."); } } } protected void ButtonAdminLogOn_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtUserName.Value) || String.IsNullOrEmpty(txtPassword.Value)) labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("<strong>Login Please!</strong><hr/>You can login using a username and a password associated with your account. Make sure that it is typed correctly."); else { //if the log-in is successful if (txtUserName.Value == "admin" && txtPassword.Value == "123123") { SiteLogin.PerformAdminAuthentication("admin", checkBoxRemember.Checked); } else { labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("<strong>Login Failed!</strong><hr/>The username and/or password you entered do not belong to any Administrator ccount on our system.<br/>You can login using a username and a password associated with your account. Make sure that it is typed correctly."); } } }

<strong>And a utility class</strong>

public static void PerformAuthentication(string userName, bool remember) { FormsAuthentication.RedirectFromLoginPage(userName, remember); if (HttpContext.Current.Request.QueryString["ReturnUrl"] == null) { RedirectToDefaultPage(); } else { HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]); } } public static void PerformAdminAuthentication(string userName, bool remember) { FormsAuthentication.RedirectFromLoginPage(userName, remember); if (HttpContext.Current.Request.QueryString["ReturnUrl"] == null) { RedirectToAdminDefaultPage(); } else { HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]); } }

My login form has two buttons: The Admin login is hard-coded name/password. The normal login routine goes back to another assembly that calls a web service and get the username and password checked against a domain login.

Now, there is one other file that has code and is baffling me.

<strong>Global.asax</strong>

<script RunAt="server"> protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity.AuthenticationType != "Forms") { throw new InvalidOperationException("Only forms authentication is supported, not " + HttpContext.Current.User.Identity.AuthenticationType); } IIdentity userId = HttpContext.Current.User.Identity; //if role info is already NOT loaded into cache, put the role info in cache if (HttpContext.Current.Cache[userId.Name] == null) { string[] roles; if (userId.Name == "admin") { roles = new string[1] { "administrators" }; } else if (userId.Name == "member1") { roles = new string[1] { "employees" }; } else { roles = new string[1] { "public" }; } //1 hour sliding expiring time. Adding the roles in cache. //This will be used in Application_AuthenticateRequest event located in Global.ascx.cs //file to attach user Principal object. HttpContext.Current.Cache.Add(userId.Name, roles, null, DateTime.MaxValue, TimeSpan.FromHours(1), CacheItemPriority.BelowNormal, null); } //now assign the user role in the current security context HttpContext.Current.User = new GenericPrincipal(userId, (string[])HttpContext.Current.Cache[userId.Name]); } } } </script>

The website has a few About pages that allow free access but the rest is either for admin or employee. My admin username/password is fixed but the employee login is entered in domain format and needs to be verified on target domain (all being done) and then set the employee role.

How am I to do that in the Application_AuthenticateRequest method in Global.asax file?

Answer1:

Set different auth modes for different folders (via <a href="http://msdn.microsoft.com/en-us/library/ms178683.aspx" rel="nofollow">Web.config</a> or even just <a href="http://technet.microsoft.com/en-us/library/cc733010%28WS.10%29.aspx" rel="nofollow">IIS snap-in</a>):

<ul><li>Anonymous for root (with about pages)</li> <li>Forms auth for ~/Admin area</li> <li>Windows/NTLM for ~/Employers area</li> </ul><hr />

Also you can use extended <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.aspx" rel="nofollow">Login control</a> with custom <a href="http://msdn.microsoft.com/en-us/library/system.web.security.membership.aspx" rel="nofollow">Membership provider</a>.

Recommend

  • Shell variable expansion - indirection while calling a utility with env
  • Calculate the depth of subclass in the OWL ontology
  • How to prevent TreeItem selection?
  • C# Dictionary ContainsKey
  • How to map childs/parent class with petapoco?
  • cordova.js for android phonegap application
  • Getting push notification payload when user opens app manually after push has been received in the b
  • Change color of row programmatically in WatchKit
  • Linked list in C, no member error
  • Conditional serialization with protobuf-net
  • Ambiguous action methods in MVC 2
  • Can someone explain the exact use of interfaces in C#?
  • Auto Height of UICollectionView inside UITableViewCell
  • Member function pointer cast, from Derived to Base class
  • Is the Go HTTP handler goroutine expected to exit immediately in this case?
  • how to save bool value in KeychainItemWrapper
  • Load 24 bit TGA
  • Visual studio alerts workspace already exists
  • Netezza Incremental load from Sql server using SSIS
  • PHP file_exists() anomaly
  • Generate a unique string based on a pair of strings
  • Deleting a widget from QTableView
  • Why is django manage.py syncdb failing to create new columns on my development server?
  • multidatatrigger with multibinding in ControlTemplate.Triggers
  • Is there a parser equivalent of 'fragment' marking in ANTLR4?
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • Configure nginx to return different files to different authenticated users with the same URI
  • HttpListener.IsSupported is false on XP SP3
  • import scipy.sparse failed
  • How to override value that appears in a dropdown in the rails_admin gem
  • Build Successful but not running on simulator
  • How do I access an unhandled exception in an MVC Error view?
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Circular dependency while pushing http interceptor
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • Linker errors when using intrinsic function via function pointer
  • Codeigniter doesn't let me update entry, because some fields must be unique
  • Getting error when using KSoap library to consume .NET web services
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET