Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change FormsCookieName at runtime in ASP.NET

We would like to have the FormsCookieName of FormsCookiePath change per instance of our application. We have an application which has multiple instances on 1 server/domainname. Because of this we can only work in 1 application at the same time, since the cookies will overwrite eachother. Same for the Sessions btw.

Is there a way to dynamicly, for example in the Global.asax Application_Start, change this name? This would be usefull as we keep a license name in each application which could be used as the basis for the CookieName.

We already work with Web.config and extra files to overwrite Web.config values in external files using: <appSettings file="Web.AppSettings.Config">

But this requires manual actions which can be forgotten and are redundant since the settings can be retrieved from the database.

Thanks.

like image 868
Gabriël Avatar asked Nov 05 '08 10:11

Gabriël


People also ask

What is FormsAuthentication in asp net?

Forms authentication enables user and password validation for Web applications that do not require Windows authentication. With forms authentication, user information is stored in an external data source, such as a Membership database, or in the configuration file for an application.

What is authentication mode in web config?

Specifies Windows as the authentication mode. This mode applies when using the Internet Information Services (IIS) authentication methods Basic, Digest, Integrated Windows (NTLM/Kerberos), or certificates.


2 Answers

I had similar situation, I did the following. In the Application_Start, I checked to see if my cookie name needed change. This would occur after a new deployment for all applications where I have the same web.config for all.


protected void Application_Start(object sender, EventArgs e)
{
  // determine unique cookie name per application
  string cookieName = ...
  // Get the web.config forms settings
  Configuration c = WebConfigurationManager.OpenWebConfiguration("~");
  AuthenticationSection auth = c.GetSection("system.web/authentication") 
        as AuthenticationSection;
  // See if we have mismatch in web.config or in Forms cookiename
  if (auth != null && auth.Forms != null && 
       (auth.Forms.Name != cookieName 
          || FormsAuthentication.FormsCookieName != cookieName
       )
     )
  {
     // Assign value in web.config for future restarts
     auth.Forms.Name = cookieName;
     // would be nice if this restarted the app, but it doesn't appear to
     c.Save();
     // This seems to restart the app
     System.Web.HttpRuntime.UnloadAppDomain();
  }
  ...
}

The web.config is modified on the application start and then the web app is restarted. Next time the web app comes up, cookie names are in sync and the reset code is skipped.

like image 165
Ron Avatar answered Oct 07 '22 17:10

Ron


I have been struggling with Cookies with quite a few days. It has been an awesome learning experience.

So wanted to share the possible ways I found & discovered: There are several HACKs to modify Forms Authentication Cookie name:

  1. You can automate the modification of cookie name under Authenticaiton secion of Web.Config file in Application_Start event in Global.asax. Thanks to Ron for sharing this. But I could not guarantee that the user whose identity would be used to run application domain have enough privileges to modify the file on disk or not. Hence I needed an improvised solution, so I devised following.

  2. Thanks to ILSpy for letting me see inside the FormsAuthentication class, and many thanks to Reflection to let me modify the private field of a class. I used following code to modify the cookie name on run-time with following small piece of code and this worked like a charm !!!


    protected void Application_Start(Object sender, EventArgs e)
    {
        // This will enforce that FormsAuthentication class is loaded from configuration settings for the application.
        FormsAuthentication.Initialize();

        // The new cookie name whatever you need can go here, I needed some value from my application setting to be prefixed so I used it.
        string newCookieName = string.Format("{0}.ASPXAUTH", ConfigurationManager.AppSettings["SomeSettingThatIsUniquetoSite"]);

        // Modifying underlying baking field that points to FormsAuthentication.FormsCookieName         
        Type type = typeof(FormsAuthentication);
        System.Reflection.FieldInfo field = type.GetField("_FormsName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
        field.SetValue(null, newCookieName);
    }

Suggestions, loopholes are requested as this is my first answer on this forum.

like image 43
Ashish Mehta Avatar answered Oct 07 '22 16:10

Ashish Mehta