What is the proper method for encrypting ASP.NET connetionStrings?

后端 未结 3 929
忘了有多久
忘了有多久 2021-02-06 17:38

I\'ve been looking through several examples of encrypting connectionStrings (Web.config) in an ASP.NET MVC application (.NET 4.0) and it seems that there are two general ways to

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 18:18

    I've come up with a solution of my own, but I'm hoping that there is a better way to do it:

    internal static class SecurityExtension
    {
        public static string GetConnetionString(this Configuration config, string databaseName, string provider = "RSAProtectedConfigurationProvider")
        {
            string sectionName = "connectionStrings";
            ConfigurationSection section = config.GetSection(sectionName);
            if (section != null && !section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection(provider);
                config.Save();
            }
    
            return WebConfigurationManager.ConnectionStrings[databaseName].ConnectionString;
        }
    }
    

    Now I just have to use the extension every time I want to get the configuration string:

    Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    string connectionString = config.GetConnetionString("MyDatabaseName");
    

    Update:
    Thanks to Brian, we can statically get the connection string:

    private static HttpRequestWrapper request = new HttpRequestWrapper(System.Web.HttpContext.Current.Request);
    private static Configuration config = WebConfigurationManager.OpenWebConfiguration(request.ApplicationPath);
    private static string connectionString = config.GetConnetionString("MyDatabaseName"));
    

    Of course you would not want to store the connection string like that, instead you would just use it to initialize your DataContext or use it for whatever else you need.

提交回复
热议问题