保护Web应用程序之外的web.config部分

时间:2011-01-07 16:36:49

标签: .net web-config

我想创建一个msbuild任务,它可以加密web.configs的某些部分。以下代码在weapplication中非常有用。将代码作为msbuild运行会导致错误,说它无法创建配置文件..

System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);

if (section != null && !section.SectionInformation.IsProtected)
{
    section.SectionInformation.ProtectSection(provider);
    config.Save();
}

我找不到能找到合适工作的班级。任何想法?

1 个答案:

答案 0 :(得分:0)

您应该创建自己的自定义MSBuild任务。

以下代码是自定义任务。

我已经完成了我的应用程序(winforms),但我标记了您可以更改为基于Web的行。

我创建了一个带有2个子类的抽象类来处理加密和解密。

干杯!

namespace MyCompany.MSBuild.Tasks.Security
{

    using System;
    using System.Linq;
    using System.Diagnostics;
    using System.Configuration;
    //using System.Web.Configuration;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public abstract class ConfigurationProtectorBaseTask : Task
    {
        private static readonly string RSA_PROVIDER = "RSAProtectedConfigurationProvider";
        private static readonly string DATA_PROTECTION_PROVIDER = "DataProtectionConfigurationProvider";

        /// <summary>
        /// Gets or sets the ExePath.  This would be the name of the .exe (or .dll) which has a corresponding .config associated with it.
        /// </summary>
        /// <value>The ExePath.</value>
        [Required]
        public string ExePath { get; set; }

        /// <summary>
        /// Gets or sets the SectionName of the configuration file you are trying to encrypt.
        /// </summary>
        /// <value>The SectionName.</value>
        [Required]
        public string SectionName { get; set; }

        /// <summary>
        /// Gets or sets the Provider.
        /// </summary>
        /// <value>The Provider.</value>
        [Required]
        public string Provider { get; set; }

        /// <summary>
        /// Task Entry Point.
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            if (!String.IsNullOrEmpty(this.Provider))
            {
                if (String.Equals(this.Provider, DATA_PROTECTION_PROVIDER, StringComparison.OrdinalIgnoreCase) || String.Equals(this.Provider, RSA_PROVIDER, StringComparison.OrdinalIgnoreCase))
                { }
                else
                {
                    Log.LogWarning(string.Format("Provider must be either '{0}' or '{1}'. Your value was '{2}'.", DATA_PROTECTION_PROVIDER, RSA_PROVIDER, this.Provider));
                    return false;
                }
            }

            if (!String.IsNullOrEmpty(this.ExePath))
            {
                Log.LogCommandLine(string.Format("{0}", this.ExePath));
                Console.WriteLine(this.ExePath);
            }

            InternalExecute();
            return !Log.HasLoggedErrors;
        }

        protected abstract void InternalExecute();

        protected Configuration GetConfiguration()
        {
            //WebVersion
            //Configuration config = WebConfigurationManager.OpenWebConfiguration(this.ApplicationPath);

            //NonAspNet version
            Configuration config = ConfigurationManager.OpenExeConfiguration(ExePath);

            return config;
        }

    }
}




namespace MyCompany.MSBuild.Tasks.Security
{
    using System;
    using System.Linq;
    using System.Diagnostics;
    using System.Configuration;
    using System.Web.Configuration;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public class ConfigurationProtectorEncrypterTask : ConfigurationProtectorBaseTask 
    {

        /// <summary>
        /// Internal Execute Wrapper.
        /// </summary>
        protected override void InternalExecute()
        {
            Configuration config = base.GetConfiguration();
            ConfigurationSection section = config.GetSection(this.SectionName);
            if (section != null && !section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection(this.Provider);
                config.Save();
            }
        }

    }
}









namespace MyCompany.MSBuild.Tasks.Security
{
    using System;
    using System.Linq;
    using System.Diagnostics;
    using System.Configuration;
    using System.Web.Configuration;

    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    public class ConfigurationProtectorDecrypterTask : ConfigurationProtectorBaseTask
    {

        /// <summary>
        /// Internal Execute Wrapper.
        /// </summary>
        protected override void InternalExecute()
        {
            Configuration config = base.GetConfiguration();
            ConfigurationSection section = config.GetSection(this.SectionName);
            if (section != null && section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
                config.Save();
            }
        }

    }
}









::::Save this as: ConfigurationProtectorTaskTest.msbuild 

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="AllTargetsWrapper" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <UsingTask AssemblyFile="MyCompany.MSBuild.dll" TaskName="ConfigurationProtectorEncrypterTask"/>
  <UsingTask AssemblyFile="MyCompany.MSBuild.dll" TaskName="ConfigurationProtectorDecrypterTask"/>


  <Target Name="AllTargetsWrapper">
    <CallTarget Targets="ConfigurationProtectorEncrypterTask1" />
    <CallTarget Targets="ConfigurationProtectorDecrypterTask2" />
  </Target>


  <PropertyGroup>
    <MyExePath>C:\SomeFolder\MyCompany.SomeExe.exe</MyExePath>
    <MySectionName>connectionStrings</MySectionName>
    <MyProvider>RSAProtectedConfigurationProvider</MyProvider>
  </PropertyGroup>



  <Target Name="ConfigurationProtectorEncrypterTask1">
    <ConfigurationProtectorEncrypterTask ExePath="$(MyExePath)" SectionName="$(MySectionName)" Provider="$(MyProvider)">
    </ConfigurationProtectorEncrypterTask>
  </Target>


  <Target Name="ConfigurationProtectorDecrypterTask2">
    <ConfigurationProtectorDecrypterTask ExePath="$(MyExePath)" SectionName="$(MySectionName)" Provider="$(MyProvider)">
    </ConfigurationProtectorDecrypterTask>

  </Target>



</Project>





:REM BAT FILE TO CALL THE ABOVE .msbuild file

call "%VS90COMNTOOLS%\vsvars32.bat"
del *.log
msbuild /target:ConfigurationProtectorEncrypterTask1 ConfigurationProtectorTaskTest.msbuild /l:FileLogger,Microsoft.Build.Engine;logfile=ConfigurationProtectorEncrypterTask1.log
msbuild /target:ConfigurationProtectorDecrypterTask2 ConfigurationProtectorTaskTest.msbuild /l:FileLogger,Microsoft.Build.Engine;logfile=ConfigurationProtectorDecrypterTask2.log

这也有帮助: http://www.codeproject.com/KB/dotnet/EncryptingTheAppConfig.aspx http://www.beansoftware.com/ASP.NET-Tutorials/Encrypting-Connection-String.aspx

但是对MSBuild Task的封装是我的贡献。

上面的第二个URL也提到了一个命令行方法:

这是引用的材料(部分引用):::

使用aspnet_regiis.exe命令行工具加密/解密

您还可以使用aspnet_regiis.exe命令行工具加密和解密Web.config文件中的部分,该工具可以在\ Microsoft.Net \ Framework \ version目录中找到。要使用此命令行工具使用DPAPI计算机密钥加密Web.config的一部分,请使用以下命令。

aspnet_regiis.exe -pe“connectionStrings”-app“/ YourWebSiteName” - “DataProtectionConfigurationProvider”

要使用此工具解密connectionStrings部分,您可以在aspnet_iisreg.exe工具中指定以下命令。

aspnet_regiis.exe -pd“connectionStrings”-app“/ YouWebSiteName”