Search code examples
c#asp.net-mvc-4cookiesforms-authentication

How to store additional data in the FormsAuthentication cookie?


I am retrieving the tenant name from the url. I'd prefer to do it only once, store it in the cookie, and retrieve it from there when I need it in a new page request.

I am using the code below to "create" a cookie. I was hoping that the interface would allow me to store additional information but it doesn't. Is there a way to do this or am I on the wrong track?

    public void SignIn(string userName, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(userName))
            throw new ArgumentException("Value cannot be null or empty.", "userName");

        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    } 

thanks in advance.


Solution

  • Personally, I wouldn't try to alter the Auth Cookie. Instead, create a new cookie:

    var myCookie = new HttpCookie("myCookie");//instantiate an new cookie and give it a name
    myCookie.Values.Add("TenantName", "myTenantName");//populate it with key, value pairs
    Response.Cookies.Add(myCookie);//add it to the client
    

    Then you can read the value on that's written to the cookie like this

    var cookie = Request.Cookies["myCookie"];
    var tenantName = cookie.Values["TenantName"].ToString();
    //tenantName = "myTenantName"