Пример #1
0
        /// <summary>
        /// calls to this method should be made inside a try catch log
        /// we don't expect the Web.config file to be writable in general but it usually is on a new 
        /// installation so we can go ahead and try to update to a custom machine key
        /// </summary>
        public static void EnsureCustomMachineKey()
        {
            SecurityAdvisor securityAdvisor = new SecurityAdvisor();

            if (securityAdvisor.UsingCustomMachineKey()) { return; } //already using a custom key

            string webConfigPath = HostingEnvironment.MapPath("~/Web.config");
            var xmlConfig = new XmlDocument();
            xmlConfig.Load(webConfigPath);

            XmlNode xmlMachineKey = xmlConfig.SelectSingleNode("/configuration/location/system.web/machineKey");
            if(xmlMachineKey == null)
            {
                xmlMachineKey = xmlConfig.SelectSingleNode("/configuration/system.web/machineKey");
            }

            string validationKey = SiteUtils.GenerateKey(128);
            string decryptionKey = SiteUtils.GenerateKey(64);

            XmlAttribute attrib = xmlMachineKey.Attributes["validationKey"];
            attrib.InnerText = validationKey;

            attrib = xmlMachineKey.Attributes["decryptionKey"];
            attrib.InnerText = decryptionKey;

            var writer = new XmlTextWriter(webConfigPath, null) { Formatting = Formatting.Indented };
            xmlConfig.WriteTo(writer);
            writer.Flush();
            writer.Close();
        }