How to set machineKey on Azure Website

Mr. Flibble picture Mr. Flibble · Apr 12, 2015 · Viewed 10.9k times · Source

I'm running an Azure Website. Whenever I deploy, everyone gets logged out because the machineKey changes.

I specified the machineKey in the web.config but this didn't solve the issue. I believe this is because Azure automatically overwrites the machineKey [1].

I've found a couple of similar questions here but the answers link to dead links.

So, what's the solution? Surely there's a way to keep users logged in regardless of deployments on Azure.

Answer

haim770 picture haim770 · Apr 21, 2015

Try to reset the machine-key configuration section upon Application_Start:

protected void Application_Start()
{
    // ...

    var mksType = typeof(MachineKeySection);
    var mksSection = ConfigurationManager.GetSection("system.web/machineKey") as MachineKeySection;
    var resetMethod = mksType.GetMethod("Reset", BindingFlags.NonPublic | BindingFlags.Instance);

    var newConfig = new MachineKeySection();
    newConfig.ApplicationName = mksSection.ApplicationName;
    newConfig.CompatibilityMode = mksSection.CompatibilityMode;
    newConfig.DataProtectorType = mksSection.DataProtectorType;
    newConfig.Validation = mksSection.Validation;

    newConfig.ValidationKey = ConfigurationManager.AppSettings["MK_ValidationKey"];
    newConfig.DecryptionKey = ConfigurationManager.AppSettings["MK_DecryptionKey"];
    newConfig.Decryption = ConfigurationManager.AppSettings["MK_Decryption"]; // default: AES
    newConfig.ValidationAlgorithm = ConfigurationManager.AppSettings["MK_ValidationAlgorithm"]; // default: SHA1

    resetMethod.Invoke(mksSection, new object[] { newConfig });
}

The above assumes you set the appropriate values in the <appSettings> section:

<appSettings>
  <add key="MK_ValidationKey" value="...08EB13BEC0E42B3F0F06B2C319B..." />
  <add key="MK_DecryptionKey" value="...BB72FCE34A7B913DFC414E86BB5..." />
  <add key="MK_Decryption" value="AES" />
  <add key="MK_ValidationAlgorithm" value="SHA1" />
</appSettings>

But you can load your actual values from any configuration source you like.