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.
Popular Articles
Recent comments
- Awsome!!
8 hours 38 min ago - C# insert image
23 hours 31 min ago - jkll
3 days 11 hours ago - Thank You
4 days 11 hours ago - Another approach
6 days 12 hours ago - Issue
1 week 1 hour ago - thanks
1 week 12 hours ago - Calendar date time
1 week 18 hours ago - Nice Explanation
1 week 22 hours ago - ramya
1 week 3 days ago

Great example...two questions/observations.
I found this extremely helpful and used the general approach to good effect in my latest project.
I do have two questions/observations however...
What is the purpose of making this a class that needs to be instantiated before each use? It has no internal state that I can discern and would surely be a perfect candidate for a static class, or if you have a dislike for static a singleton that can be instantiated once and only once and then used from anywhere.
Secondly, I found it unwise to need to understand the structure of the identity data inside the AuthenticationManager. It means that authentication is not a black box and that changes to the identity data necessitate changes to the authentication class. The encoding and decoding of the identity string is in effect support for the serialization of an identity structure and I found it better explicitly coded as such with the authentication code only ever handling the resulting string.
Anyway, two minor points that I chose to handle differently, and should not detract from the well laid out and commented example. Thank you.
A response to your observations
Yes, this would very easily be a static class or at the very least, a series of static methods within this class. There is no intrinsic state so it shouldn't cause any problems to make this static. This also saves a line of code everytime you use it so it's a good point.
On the second for the implementation details when serializing the user's data, I agree. It can be more hidden. In some ways, I think I did it this way so it was clearer when I posted the article about what was happening. Feel free to hide it or post your changes here. Thanks!