Close this search box.

Forms Authentication in ASP.NET

I was explaining Forms authentication in the ASP.NET forums and thought of writing about it (very basic stuff). See the below sample entry in the config file:

<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="/private/login.aspx" protection ="All" timeout="20" path="/" slidingExpiration="true">
forms >

    <deny users="?" />

It is important to have the element after the element to deny access to anonymous users and redirect them to the login page.

Path tag is used to specify the virtual path to which the cookie applies. “/” is the recommened setting (also the default). This value is transmitted in the cookie itself and implies that the Forms Authentication is applicable to all pages, folders and sub folders in the application root. If you change this value to some specific folder (lets say “/Sub Folder“), then you need to make sure that every link where any Page inthe app is referenced is proper cased, else authentication won’t work (Login page will reappear even after you supply the right credentials).

The web.config setting is for the cookie created automatically when you use FormsAuthentication.RedirectFromLoginPage() method, but you are creating a cookie explicitly and you need to set the expiry manually for it. I do not understand the need for you to create your own cookie (unless some business requirement is there, like using persistent cookies).

Also, you need to make sure that the client machine is set to accept cookies, if not (which is rare), then use URL munging. The runtime will place the authentication ticket in the querystring in this case (if you use  FormsAuthentication.CookiesSupported = false). Note that FormsAuthentication.RedirectFromLoginPage() method calls theSethAuthCookie() method in it, so no need to create the cookies manually. the cookie will be automatically encrypted. See the source code of RedirectFromLoginPage method below:

public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
      if (userName != null)
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie, strCookiePath);
            HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, createPersistentCookie), false);

Below are the important lines from the GetAuthCookie() method which is called by SetAuthCookie() internally (notice how the cookie value is encrypted):

 FormsAuthenticationTicket ticket1 = new FormsAuthenticationTicket(1, userName, DateTime.Now, createPersistentCookie ? DateTime.Now.AddYears(50) : DateTime.Now.AddMinutes((double) FormsAuthentication._Timeout), createPersistentCookie, "", strCookiePath);
      string text1 = FormsAuthentication.Encrypt(ticket1);
 HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, text1);

So you do not need to write explicit code, just write the code to authenticate and then redirect as:

Page.Validate();  //make sure to fire all validators


if (CheckLogin(Username, Password)) //CheckLogin is a custom method to see if username and pwd are right or not. it returns a boolean value


    FormsAuthentication.RedirectFromLoginPage(Username, false);

Also, note that as soon as the user closes his/her browser, the cookie will expire and he/she will need to login again. In ASP.NET 1.1, in order to create a persistent cookie,]

you need to create an object of HttpCookie yourself (using FormsAuthentication.GetAuthCookie() method, set its expiry and add it to the Response object. This cookie will expire if FormsAuthentication.SignOut()

method is called or the cookie validity expires Here is some sample code after successful username and password validation:

HttpCookie cookie = FormsAuthentication.GetAuthCookie(Username,true); //true is used to create a persistent cookie

cookie.Expires = DateTime.Now.AddMonths(3); //this will expire after 3 months


Response.Redirect(FormsAuthentication.GetRedirectUrl(Username,true);//redirect to the originally requested page

Note that the timeOut value in the config file has no influence on persistent cookies (in ASP.NET 1.1 only). But in ASP.NET 2.0, the above code will not work,

as the persistent cookies themselves take the timeout value from the config file. See this post for details:

Also, you can get the userName from the cookie itself.

//GethAuthCookie puts the user name in an object of FormsAuthenticationTicket and later calls the 
//FormsAuthentication.Encrypt(ticket) method. You can access this value as:

protected void Page_Load(object sender, EventArgs e)
   HttpCookie loginCookie = Request.Cookies["Test"];  //"Test" is the cookie name specified in the config file.
   FormsAuthenticationTicket t = FormsAuthentication.Decrypt(loginCookie.Value);
   string userName = t.Name; //this is the userName stored while cookie was created as HttpCookie cookie = FormsAuthentication.GetAuthCookie(Username, true);

But use this code only when needed since many times using the Session is more helpful as cookies can be tampered at client side. In case
you need persistent cookies, then this is ok. But it is recommended that you expire cookies as soon as possible (besides keeping Session timeouts as low as possible).

Make sure you use SSL so that the username and passwords sent remotely are secure!

This article is part of the GWB Archives. Original Author: Vivek Thakur

Related Posts