Click here to Skip to main content
15,867,780 members
Articles / Web Development / ASP.NET

Permanent User Login Session In ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.77/5 (17 votes)
8 Oct 2011CPOL3 min read 98.9K   7.5K   87   9
Create a permanent login session using customized cookie

Introduction

This article describes how to create a permanent user login session in ASP.NET. The sample code includes an ASP.NET MVC4 project to control the user registration and login process. But you can use this technique in any type of ASP.NET project.

Forms Authentication

Before getting into the depth of this article, you must be familiar with forms authentication in ASP.NET. The configuration of form authentication resides in web.config file which has the following configuration-file fragment with the assigned values.

XML
<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" 
             protection="All"
             timeout="1"
             name=".USERLOGINCONTROLAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="~/Home/Index"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false"/></authentication>

The default values are described below: 

  • loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.
  • 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 is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.
  • name and path are set to the values defined in the application's configuration file.
  • requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.
  • slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.
  • defaultUrl is set to the Default.aspx page for the application.
  • cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.
  • enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

FormsAuthentication.SetAuthCookie Method

This method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication. The first overload of this function has two parameters:

  • userName: The name of the authenticated user
  • createPersisntentCookie: True to create a persistent cookie (one that is saved across browser sessions); otherwise, false.

This method add a cookie or persistent cookie to the browser with an expire time set in "timeOut" parameter with the name and path set in "name" and "path" parameter. The user will be automatically logged out once the cookie is expired. So the user login session depends on the expire of forms authentication ticket saved in browser cookie. Here, I will create a permanent user login session using this technique.

Cookie Helper

The functionality of this class is to add a form authentication ticket to the browser cookie collection with a life time expiry.

C#
public sealed class CookieHelper
{
    private HttpRequestBase _request;
    private HttpResponseBase _response;

    public CookieHelper(HttpRequestBase request, 
	HttpResponseBase response)
	{
		_request = request;
		_response = response;
	}

    //[DebuggerStepThrough()]
    public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
    {
        if (_response != null)
        {
            if (isPermanentCookie)
            {
                FormsAuthenticationTicket userAuthTicket = 
                	new FormsAuthenticationTicket(1, userName, DateTime.Now, 
                	DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
                string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
                HttpCookie userAuthCookie = new HttpCookie
                	(FormsAuthentication.FormsCookieName, encUserAuthTicket);
                if (userAuthTicket.IsPersistent) userAuthCookie.Expires = 
						userAuthTicket.Expiration;
                userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
                _response.Cookies.Add(userAuthCookie);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
            }
        }
    }
}

This function is used in login page or control on the click of login button. In the attached sample project, the following function is written in AccountController class. This function validates the login of the user and then add a permanent form authentication ticket to the browser.

C#
private bool Login(string userName, string password,bool rememberMe)
{
    if (Membership.ValidateUser(userName, password))
    {
        CookieHelper newCookieHelper = 
		new CookieHelper(HttpContext.Request,HttpContext.Response);
        newCookieHelper.SetLoginCookie(userName, password, rememberMe);
        return true;
    }
    else
    {
        return false;
    }
} 

Points of Interest

So in this way, you can control the forms authentication ticket to control the login session of a user.

History

  • 9th October, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Ominto Inc
United Arab Emirates United Arab Emirates
I am Bachelor in CSE from Khulna University of Engineering & Technology,Bangladesh. I have more than 11 years experience in software design & development, data analysis & modeling, project management and currently working in a software company in Dubai,UAE as a Lead Software Engineer. I am MCAD(Microsoft Certified Application Developer) certified since 2005. Please feel free to contact with me at nill_akash_7@yahoo.com.


Comments and Discussions

 
QuestionHow to read this cookie by c# code Pin
M. Salah AbdAllah8-Mar-17 22:10
professionalM. Salah AbdAllah8-Mar-17 22:10 
QuestionForm authentication with URL rewriting issue Pin
Muthu Nadar5-May-15 4:09
Muthu Nadar5-May-15 4:09 
QuestionAn object reference is required for the non-static field, method or prop Pin
Abdallah Al-Dalleh7-Aug-14 5:24
Abdallah Al-Dalleh7-Aug-14 5:24 
QuestionGreat article! Pin
Mo Kash28-Aug-13 22:30
Mo Kash28-Aug-13 22:30 
Question2 thumbs Up Pin
giliteen30-Oct-12 23:27
giliteen30-Oct-12 23:27 
QuestionHow do I open this project? Pin
jp2code6-Mar-12 8:36
professionaljp2code6-Mar-12 8:36 
General5 for this Great Work Pin
genious Developer21-Oct-11 22:01
genious Developer21-Oct-11 22:01 
GeneralMy vote of 5 Pin
Ahsan Murshed11-Oct-11 22:42
Ahsan Murshed11-Oct-11 22:42 
GeneralMy vote of 5 Pin
rakak11-Oct-11 9:55
rakak11-Oct-11 9:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.