Reply to comment
ASP.NET Forms Authentication Simplified
There are so many tutorials online about Forms Authentication or other auth methods in ASP.NET that it is sometimes hard to wade through and get what you need. I've made a very simple wrapper class that you can include in your ASP.NET project to give you out of the box, basic forms authentication.
This class provides methods to log a user in and set their authentication cookie, logout, and check if the cookie exists on a page load to insure a user is authenticated before granting them access. There are ways to do all of this from the web.config but I rarely can use those simple methods because my authentication needs are usually more advanced than just blanket allowing/disallowing a set of pages. Here's the code for the class with comments:
// provides methods to log a user into public class FormsAuthManager
{ // this is used to store the user's primary key, display name, and other details // in the "Identity UserName" property so that we can parse them out later // without having to do an additional database query.private const string DELIM = "~";
public FormsAuthManager() { // constructor}
// private methods // concats the user's display name and primary key id so that we can store them // in the identity string of the cookie.private string _BuildIdentity(string sUserId, string sDisplayName)
{ return sUserId + DELIM + sDisplayName;}
// retrieves the display name for the user from what was put in the auth cookie.public string GetDisplayName(System.Web.UI.Page currentPage)
{string sDisplayName = "";
// get the user's identity for the current page string sIdentity = currentPage.User.Identity.Name; string[] sArray = sIdentity.Split(DELIM.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (sArray.Length > 1) {sDisplayName = sArray[1];
}
return sDisplayName;}
// retrieves the primary key id of the user from what was put in the auth cookie.public string GetUserId(System.Web.UI.Page currentPage)
{string sUserId = "";
string sIdentity = currentPage.User.Identity.Name; string[] sArray = sIdentity.Split(DELIM.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (sArray.Length > 0) {sUserId = sArray[0];
}
return sUserId;}
// public methods // builds the identity for the user and sets the auth cookie to log // them in. Call this method when your login was successful. Also // redirects user to the default page when login is correct.public void AuthenticateUser(string sUserId, string sDisplayName)
{ // get the default url to redirect to from the web.config and redirect the user string sDefaultUrl = System.Web.Security.FormsAuthentication.DefaultUrl; // call authenticate user with the default url specified as the URL // to redirect from.AuthenticateUser(sUserId, sDisplayName, sDefaultUrl);
}
// overload for AuthenticateUser allows you to specify a redirect URL to override the // defaultUrl property in the web.config. This is useful if you are in a sub-directory // page and need to redirect to another sub-domain.public void AuthenticateUser(string sUserId, string sDisplayName, string sRedirectUrl)
{ string sDomain2 = System.Web.Security.FormsAuthentication.CookieDomain; // set up the user's identity and set the auth cookie. string sIdentity = _BuildIdentity(sUserId, sDisplayName); System.Web.Security.FormsAuthentication.SetAuthCookie(sIdentity, true); // if there is a domain specified in the web.config, use it in the cookie // so that the cookie can work across sub-domains of this domain. // This is useful for sub-domain environments. string sDomain = System.Web.Security.FormsAuthentication.CookieDomain;if (!string.IsNullOrEmpty(sDomain))
{ HttpCookie cookie = System.Web.Security.FormsAuthentication.GetAuthCookie(sIdentity, true);cookie.Domain = sDomain;
HttpContext.Current.Response.Cookies.Add(cookie);
}
// redirect to the URL specified.HttpContext.Current.Response.Redirect(sRedirectUrl);
}
// check if the user is authenticated. returns true if authenticated and // false otherwise.public bool CheckIsAuthenticated(System.Web.UI.Page currentPage, string sRedirectUrl)
{ bool bIsAuthenticated = currentPage.User.Identity.IsAuthenticated; if (bIsAuthenticated) { return bIsAuthenticated;}
else { // user is not authenticated so redirect back to the page specifiedHttpContext.Current.Response.Redirect(sRedirectUrl);
return bIsAuthenticated;}
}
// overload for CheckIsAuthenticated() that uses the url specified in the web.config // to redirect to the login pagepublic bool CheckIsAuthenticated(System.Web.UI.Page currentPage)
{ // get the login url from the web.config settings string sLoginUrl = System.Web.Security.FormsAuthentication.LoginUrl; // call overload method to check auth and redirect if necessary. return CheckIsAuthenticated(currentPage, sLoginUrl);}
// logs the user out and removes the auth cookie. Also redirects // back to the login page designated in the web.config.public void Logout()
{ // navigate back to the login page string sLoginUrl = System.Web.Security.FormsAuthentication.LoginUrl; // call Logout() to redirect after login to the LoginUrl we read // from the web.configLogout(sLoginUrl);
}
// overload for Logout() that redirects to the URL specified. This is // useful when you want to redirect to a different page instead of the // login url specified in the web.config.public void Logout(string sRedirectUrl)
{System.Web.Security.FormsAuthentication.SignOut();
string sCookieName = System.Web.Security.FormsAuthentication.FormsCookieName; // for safety, also set the cookie to expire right nowHttpContext.Current.Response.Cookies[sCookieName].Expires = DateTime.Now;
// navigate to the user specifiedHttpContext.Current.Response.Redirect(sRedirectUrl);
}
}
Using this class makes it incredibly easy to get authentication set up in a matter of minutes on a site. First, place a new section in your web.config that looks something like this:
<authentication mode="Forms">
<forms name=".MYUNIQUECOOKIENAME"
loginUrl="Login.aspx"
protection="All"
timeout="1440"
slidingExpiration="true"
defaultUrl="Default.aspx"
domain="devtoolshed.com" />
</authentication>
NOTE: This XML goes anywhere inside of the
Here is a definition of what these XML attributes mean/do:
- name - the unique name of your cookie. Name it something specific to your site or domain and application so it doesn't collide with other cookies on this domain.
- loginUrl - the URL to navigate to when login is successful.
- protection - is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.
- timeout - the number of minutes for the cookie to exist before it expires.
- slidingExpiration - whether or not you want the cookie's expiration to slide meaning that each time the user authenticates again, their cookie will set the timeout start point to the current time.
- defaultUrl - the URL to navigate to when the user is not authenticated or the cookie expires or the user logouts.
- domain - optionally you can specify the domain of your site so that your cookie can persist across sub-domains of this domain. Do not add this attribute if you are debugging locally.
In your login page, on the method that logs the user in, after you check the username and password to make sure they are valid, you can authenticate the user like this:
// get the user's primary keystring sUserId = "1234";
// get the user's display namestring sDisplayName = "";
// creat new instance of forms auth classFormsAuthManager authManager = new FormsAuthManager();// authenticate user by setting auth cookie and redirects// them to the default url.authManager.AuthenticateUser(sUserId, sDisplayName);
Now in the method to logout, you can place this code to log the user out and remove their auth cookie:
// creat new instance of forms auth classFormsAuthManager authManager = new FormsAuthManager();// log the user outauthManager.Logout();
Finally, on each page that you want to check to see if the user is logged in, you can place this code:
// creat new instance of forms auth classFormsAuthManager authManager = new FormsAuthManager();// check if user is authenticated. NOTE: we have to // pass the current Page in so we can check it for // authentication.if (authManager.CheckIsAuthenticated(Page)){ // get the user's primary key string sUserId = authManager.GetUserId(Page); // get the user's display name if you need it string sDisplayName = authManager.GetDisplayName(Page);}
You can use the overloads to specify a URL to redirect from instead. Now this class is portable so you can get authentication running on other sites in a matter of minutes.
Reply
Popular Articles
Last viewed:
- Add a Composite Control to the Visual Studio Toolbox
- Install Windws 2003 Terminal Service Licenses (Remote Desktop)
- Deploy Crystal Reports 2008 Run-time on Remote Server
- Override Default SPAN Tag for Composite Controls
- Get the list of ODBC data source names programatically using C#
- SQL Server Database Project and Database Source Control

Recent comments
1 day 19 hours ago
6 days 9 hours ago
6 days 10 hours ago
1 week 18 hours ago
1 week 2 days ago
2 weeks 8 hours ago
2 weeks 1 day ago
2 weeks 4 days ago
2 weeks 6 days ago
2 weeks 6 days ago