How to use Persistent Cookies with Forms Authentication in ASP.NET in VB.NET

Usually you will use in your projects nonpersistent authentication cookie to maintain the authentication ticket between requests. This means that if the user closes the browser, the cookie is immediately removed. The benefits are the following:

– This is a sensible step that ensures security. It’s particularly important with shared computers to prevent another user from using a previous user’s ticket.

– Nonpersistent cookies also make session hijacking attacks (where a malicious user gains access to the network and steals another user’s cookie) more difficult and more limited.

In some situation you can decide to use persistent authentication cookies. If you are performing authentication for personalization instead of controlling access to restricted resources, you may decide that the usability advantages of not requiring users to log in on every visit compensate the increased danger of unauthorized use. You can use persistent cookies, by supplying a value of true rather than false for the second the second parameter of the RedirectFromLoginPage() or SetAuthCookie() method of the FormsAuthentication class:

FormsAuthentication.RedirectFromLoginPage(UsernameText.Text, True)

Persistent cookies do not expire when the browser is closed. They expire when you call the FormsAuthentication.SignOut() method or when they reach the time limit set in the timeout attribute of the <forms> element (by default, 30 minutes). This raises a potential problem. In some applications, you might want to give users the choice of using a short-term nonpersistent cookie or storing a long-lived persistent cookie. However, you can only set the timeout attribute to one value. The solution is to use the GetAuthCookie() method of the FormsAuthentication class to create your persistent cookie, set the expiry date and time by hand, and then write the persistent cookie to the HTTP response yourself.

The following example rewrites the code that authenticates the user when the login button is clicked. It creates a persistent cookie but performs additional steps to give the cookie a 7-day life span:

 

Protected Sub LoginAction_Click(sender As Object, e As EventArgs)

Page.Validate()

If Not Page.IsValid Then

Return

End If

If FormsAuthentication.Authenticate(UsernameText.Text, PasswordText.Text) Then

‘ 1. Create the authentication cookie

Dim AuthCookie As HttpCookie

AuthCookie = FormsAuthentication.GetAuthCookie(UsernameText.Text, True)

 

‘2. Set expiry date and time of the cookie

AuthCookie.Expires = DateTime.Now.AddDays(7)

 

‘3. Add the cookie to the response

Response.Cookies.Add(AuthCookie)

 

‘ 4. Redirect the user to the originally requested page

Response.Redirect(FormsAuthentication.GetRedirectUrl(UsernameText.Text, True))

Else

‘ User name and password are not correct

LegendStatus.Text = “Invalid username or password!”

End If

End Sub

 

1. In the code the authentication cookie isn’t added automatically. Instead, it’s created with a call to GetAuthCookie(), which returns a new instance of HttpCookie, as shown here:

     

    Dim AuthCookie As HttpCookie

    AuthCookie = FormsAuthentication.GetAuthCookie(UsernameText.Text, True)

     

    2. Once you’ve created the authentication cookie, you can retrieve the current date and time (using the DateTime.Now static property), add seven days to it (using the DateTime.AddDays() method), and use this value as the expiry date and time of the cookie:

       

      AuthCookie.Expires = DateTime.Now.AddDays(7)

       

      3. Now, you have to add the cookie to the HTTP response:

         

        Response.Cookies.Add(AuthCookie)

         

        4. Finally, you can redirect the user to the originally requested URL, which you can obtain by using the GetRedirectUrl() method:

           

          Response.Redirect(FormsAuthentication.GetRedirectUrl(UsernameText.Text, True))

           

          The end result is a cookie that will persist beyond the closing of the browser but that will expire after seven days, at which point the user will need to reenter credentials to log into the website.