{"id":72447,"date":"2017-09-06T17:22:06","date_gmt":"2017-09-06T17:22:06","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=72447"},"modified":"2021-06-03T16:47:00","modified_gmt":"2021-06-03T16:47:00","slug":"managing-password-applications-user","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/managing-password-applications-user\/","title":{"rendered":"Managing the Password of the Application&#8217;s User"},"content":{"rendered":"<p>When we use Windows Authentication, Active Directory enforces password policy for the users, including expiration policy. This was an unwelcome difference between window and SQL Logins until SQL Server 2012, when SQL Server started to enforce windows password policies to SQL Server logins by default.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"475\" height=\"302\" class=\"wp-image-72448\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image.png\" \/><\/p>\n<p class=\"caption\">Policy settings for SQL Server Login<\/p>\n<p>However, most people will ask why this is necessary. Only a user that is connecting directly to SQL Server in <strong>SSMS<\/strong> is able to change his password when it expires and the majority of SQL Server users will connect through some application which, in turn, connects to SQL Server using a single login created for it.<\/p>\n<p>The application login is stored by the application in some kind of configuration file. In <strong>.NET<\/strong>, they are stored in the <strong>.config<\/strong> files with their passwords. In this case, why would you want to enforce domain password policy, if the application won&#8217;t be able to change the password anyway?<\/p>\n<p>The answer is, of course, that you wouldn\u2019t but what if the application could, in fact, change the password? Then an expiration policy makes sense. I will show in this article how we can achieve a security regimen where the application can conform to the password policy requirements automatically and no one, not even the developers, database or IT administrators, will know the password used by the application, thereby enhancing the security of our application environment.<\/p>\n<h2>Development Environment for this article<\/h2>\n<p>I&#8217;m using <strong>SQL Server 2017 CTP 2.1<\/strong> and <strong>Visual Studio 2017<\/strong> to develop this solution, but I will use a library from <strong>SQL Server 2014<\/strong>, as I will explain later in the article.<\/p>\n<p>You can use different <strong>Visual Studio<\/strong> versions, but the solution as it stands will only work with <strong>Entity Framework 6.0<\/strong> and later.<\/p>\n<p>You will also need <strong>IIS (Internet Information Server)<\/strong> configured on the machine so you can simulate the deployment process.<\/p>\n<p>I will use the <em>\u2018Northwnd\u2019<\/em> sample database, which you can download from <a href=\"https:\/\/northwinddatabase.codeplex.com\/\">here<\/a>. I will restore the <em>\u2018Northwnd.bak\u2019<\/em> file twice, creating two databases: <em>\u2018Northwnd\u2019<\/em> and <em>\u2018NorthProduction\u2019<\/em>.<\/p>\n<p>We will start with an existing small solution with two projects. You can download the starting solution from this link: <a href=\"https:\/\/github.com\/DennesTorres\/ChangePassword\/tree\/master\/slCustomersStarting\">https:\/\/github.com\/DennesTorres\/ChangePassword\/tree\/master\/slCustomersStarting<\/a> . One of the projects is an <strong>MVC Web Application<\/strong> with a single controller and view. The controller accesses customers\u2019 information in the <em>\u2018Northwnd\u2019<\/em> database and exposes this information to the view. The database access is executed by the second project, a class library with the Entity Framework context.<\/p>\n<h2>The use of the password in the development process<\/h2>\n<p>How can we manage our development and deployment process without knowing the password for the database server?<\/p>\n<p>Let\u2019s suppose we have three environments: Development, QA\/Test and Production. Developers need access to the development environment, so we can\u2019t hide the password in this environment. QA\/Test and Production, however, can have a stricter access control.<\/p>\n<p>When the application is published from development to QA\/Test, and thence to Production, the connection string is changed. Some people still do it manually, however, we have <strong>web.config<\/strong> transformations to do it for us during the publishing process.<\/p>\n<p>The secret here is in the database layer: Each time a new deployment is completed, the DBA needs to reset the password for the database login to a starting password known by the deployment process and configured in the <strong>web.config<\/strong>.<\/p>\n<p>The login needs to be configured with <strong>\u2018User must change password at next login\u2019<\/strong> configuration, so the application will change the password during the first login after the deployment and no one but the application will know the new password.<\/p>\n<p>However, after the password change, the password will be inside the <strong>web.config<\/strong>, won\u2019t it? Yes, it will, but the IT team can encrypt the <strong>web.config <\/strong>during the deployment process. It\u2019s already difficult to have access to the <strong>web.config<\/strong>, only some members of the IT team have this kind of access, with the automatic encryption the access will be even more restrict and we will achieve the objective: No one but the application will know the password.<\/p>\n<p>In this article, I will build the application and test it as it was in the QA\/Test environment and do some steps of the deployment process to the Production environment.<\/p>\n<h2>The Solution<\/h2>\n<p>Our solution needs to change the login password every time it expires, or when the login is marked with the <strong>&#8216;User must change password at next logon&#8217; <\/strong>option. We will need to break the solution in parts to achieve a better code organization. These will be the parts of our solution:<\/p>\n<ul>\n<li><strong>Part I: A class to change SQL Server login password. <\/strong>\n<p>This class will receive a connection string and change the password in the server and in the connection string<\/p>\n<\/li>\n<li><strong>Part II: A class to change the connection string in the .config file<\/strong>\n<p>Our solution can be used from a web application or a desktop application. This class will need to identify it and open the correct <strong>.config<\/strong> file (<strong>app.config<\/strong> or <strong>web.config<\/strong>).<\/p>\n<\/li>\n<li><strong>Part III: Intercept and identify connection errors<\/strong>\n<p>In this article, I will focus on Entity Framework and I will demonstrate how to use the retry strategy to intercept errors and identify whether the reason was the password.<\/p>\n<\/li>\n<\/ul>\n<h3>Preparing the Logins<\/h3>\n<p>Before starting the development, we need to configure the SQL Server logins for QA\/Test and Production environments. These will be our first steps:<\/p>\n<ol>\n<li>Open <strong>SSMS<\/strong> (<strong>SQL Server Management Studio<\/strong>)<\/li>\n<li>Inside <strong>Object Explorer <\/strong>window, below your server, open folders <em>\u2018Security\u2019<\/em> -&gt; <em>\u2018Logins\u2019<\/em><\/li>\n<li>Right-click the <em>\u2018Logins\u2019<\/em> folder and click <em>\u2018New Login\u2019<\/em> item in the context menu\n<p><img loading=\"lazy\" decoding=\"async\" width=\"382\" height=\"347\" class=\"wp-image-72449\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-1.png\" \/><\/p>\n<\/li>\n<li>In the <em>\u2018Login \u2013 New\u2019<\/em> window, type <em>\u2018usrQuality\u2019<\/em> in the \u2018Login Name\u2019 textbox<\/li>\n<li>Select <em>\u2018SQL Server Authentication\u2019<\/em> radio button<\/li>\n<li>Type <em>\u2018Pa$$w0rd\u2019<\/em> in the <em>\u2018Password\u2019<\/em> textbox<\/li>\n<li>Type <em>\u2018Pa$$w0rd\u2019<\/em> in the <em>\u2018Confirm Password\u2019 <\/em>textbox<\/li>\n<li>Click in the checkbox <em>\u2018User must change password at next login\u2019<\/em> and keep it checked\n<p><img loading=\"lazy\" decoding=\"async\" width=\"859\" height=\"777\" class=\"wp-image-72450\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-2.png\" \/><\/p>\n<\/li>\n<li>In the left side of <em>\u2018Login \u2013 New\u2019<\/em> window, below <em>\u2018Select a page\u2019<\/em>, click <em>\u2018User Mappings\u2019<\/em><\/li>\n<li>Inside the <em>\u2018Users mapped to this login\u2019 <\/em>box, click the checkbox besides the <em>\u2018Northwnd\u2019<\/em> database, keep it checked<\/li>\n<li>Inside the <em>\u2018Database role membership for: Northwnd\u2019 <\/em>box, click the checkbox besides <em>\u2018db_datareader\u2019<\/em> role, keep it checked.<\/li>\n<li>Inside the <em>\u2018Database role membership for: Northwnd\u2019 <\/em>box, click the checkbox besides <em>\u2018db_datawriter\u2019<\/em> role, keep it checked.<\/li>\n<li>Click the <em>\u2018Ok\u2019 <\/em>button\n<p><img loading=\"lazy\" decoding=\"async\" width=\"859\" height=\"779\" class=\"wp-image-72451\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-3.png\" \/><\/p>\n<\/li>\n<li>Repeat steps 2 to 13 for the login <em>\u2018usrProduction\u2019<\/em><br \/>\n<h3>Part I: Changing SQL Server login password<\/h3>\n<p>We can&#8217;t use a regular <strong>ADO.NET<\/strong> or <strong>Entity Framework<\/strong> connection to change the login password, especially because the password will be expired and we can&#8217;t connect.<\/p>\n<p>SQL Server has a different set of objects, <strong>SMO<\/strong> (<strong>SQL Server Management Objects<\/strong>), which we can use to execute management tasks in the server, including a change of the password.<\/p>\n<p><strong>SMO<\/strong> can be installed with the SQL Server installation, choosing <strong>Client Tools SDK<\/strong> during the installation. There are some other installation options, you can see details <a href=\"https:\/\/docs.microsoft.com\/pt-br\/sql\/relational-databases\/server-management-objects-smo\/installing-smo\">here<\/a><\/p>\n<p>We need only a single assembly: <strong>Microsoft.SqlServer.ConnectionInfo.dll. <\/strong>This assembly exists for each SQL Server version, however, after some tests, I was able to change the password of a login in SQL Server 2017 using the assembly from SQL Server 2014. Due to that, I saw no need to use some design pattern, such as provider model, to turn flexible the use of this library.<\/p>\n<p>According the SQL Server version, this assembly can be in <em>\u2018C:\\Program Files\\Microsoft SQL Server\\&lt;version number&gt;\\SDK\\Assemblies\u2019<\/em> or <em>\u2018C:\\Program Files (x86)\\Microsoft SQL Server\\&lt;version number&gt;\\SDK\\Assemblies\u2019<\/em>. Until version 120 (SQL Server 2014), the assembly uses the first path, after that uses the second.<\/p>\n<p>Let&#8217;s do a step-by-step walk-through to start the creation of our solution and implement this first class:<\/p>\n<\/li>\n<li>Open the starting solution in <strong>Visual Studio<\/strong><\/li>\n<li>Create the project <em>\u2018libPassword\u2019<\/em>\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018slHints\u2019<\/em> solution and click <em>\u2018Add\u2019<\/em>-&gt;<em>\u2019New Project\u2019<\/em> in the context menu<\/li>\n<li>In the right side of the <em>\u2018New Project\u2019 <\/em>window, select \u2018<em>Installed\u2019-&gt;\u2019Templates\u2019-&gt;\u2019Visual C#\u2019-&gt;Windows<\/em> in the tree<\/li>\n<li>In the middle of the <em>\u2018New Project\u2019 <\/em>window, select <em>\u2018Class Library\u2019<\/em> project template<\/li>\n<li>In the <em>\u2018Name\u2019<\/em> textbox, type <em>\u2018libPassword\u2019<\/em> and click <em>\u2018Ok\u2019<\/em> button\n<p><img loading=\"lazy\" decoding=\"async\" width=\"951\" height=\"660\" class=\"wp-image-72452\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-4.png\" \/><\/p>\n<\/li>\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018Class1.cs\u2019<\/em> file, below the <em>\u2018libDados\u2019<\/em> project, and click <em>\u2018Delete\u2019<\/em> in the context menu<\/li>\n<\/ol>\n<\/li>\n<li>Add reference to <strong>Microsoft.SqlServer.ConnectionInfo.dll<\/strong>\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018libPassword\u2019<\/em> project and click <em>\u2018Add\u2019<\/em>-&gt;<em>\u2019Reference\u2019 <\/em>in the context menu<\/li>\n<li>In the <em>\u2018Reference Manager\u2019<\/em> window, click <em>\u2018Browse\u2019<\/em> button<\/li>\n<li>Navigate to the correct folder and select the file <strong>Microsoft.SqlServer.ConnectionInfo.dll<\/strong>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"964\" height=\"576\" class=\"wp-image-72453\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-5.png\" \/><\/p>\n<\/li>\n<li>Click <em>\u2018Ok\u2019<\/em> button<\/li>\n<\/ol>\n<\/li>\n<li>Create a new class called <em>&#8216;SQLChangePassword&#8217;<\/em>\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018libPassword\u2019<\/em> project and click <em>\u2018Add\u2019<\/em>-&gt;<em>\u2019Class\u2019<\/em> in the context menu<\/li>\n<li>Type <em>\u2018SQLChangePassword.cs\u2019<\/em> in the <em>\u2018Name\u2019<\/em> textbox and click the <em>\u2018Ok\u2019<\/em> button<\/li>\n<\/ol>\n<\/li>\n<li>Add the following lines to the top of the file <em>&#8216;SQLChangePassword.cs&#8217;<\/em>, just below the <em>&#8216;Using&#8217;<\/em>s:\n<pre class=\"theme:vs2012 lang:c# decode:true\">using Microsoft.SqlServer.Management.Common;\r\n  using System.Data.SqlClient;<\/pre>\n<\/li>\n<li>Create the method <em>&#8216;ChangePwd&#8217;<\/em> in the <em>\u2018SQLChangePassword\u2019<\/em> class using the following code:\n<pre class=\"theme:vs2012 lang:c# decode:true\">        public static string ChangePwd(string ConnectionString, \r\n  string newPassword)\r\n          {\r\n              var builder = new SqlConnectionStringBuilder(ConnectionString);\r\n              ServerConnection srvConn = new ServerConnection();\r\n              srvConn.ServerInstance = builder.DataSource;\r\n              srvConn.LoginSecure = false;\r\n              srvConn.Login = builder.UserID;\r\n              srvConn.Password = builder.Password;\r\n              srvConn.ChangePassword(newPassword);\r\n              builder.Password = newPassword;\r\n              return builder.ConnectionString;\r\n          }<\/pre>\n<p>This method uses two classes:<\/p>\n<ul>\n<li><strong>SqlConnectionStringBuilder<\/strong>: This class is responsible to break the connection string in several pieces, so we can use each connection information.<\/li>\n<li><strong>ServerConnection:<\/strong> This is the SMO class responsible for the SQL Server connection and with a method to change the password.<\/li>\n<\/ul>\n<h3>Part II: Saving the new password in the .config file<\/h3>\n<p>The main library of our solution is <em>\u2018libPassword\u2019<\/em>, all other projects are there only for the example. If our library is running as a desktop application, we need to save the password in the <strong>app.config<\/strong> file. However, if the library is running in a web application, we need to save the password in the <strong>web.config<\/strong>.<\/p>\n<p>In both cases, we need to retrieve an instance of the <em>&#8216;Config&#8217;<\/em> class, change the value and use the <strong>save<\/strong> method. However, for the desktop application we will use <em>&#8216;ConfigurationManager&#8217;<\/em> to retrieve the <em>&#8216;Config&#8217;<\/em> instance, while for the web application we will use <em>&#8216;WebConfigurationManager&#8217;<\/em> for this task.<\/p>\n<p>We can use the value of <strong>HttpRuntime.AppDomainAppId <\/strong>to identify whether our library is running in a web application or desktop application.<\/p>\n<p>Let&#8217;s continue our walk-through:<\/p>\n<\/li>\n<li>Create the class <em>&#8216;SetConnectionConfig&#8217;<\/em>\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018libPassword\u2019<\/em> project and click <em>\u2018Add\u2019<\/em>-&gt;<em>\u2019Class\u2019<\/em> in the context menu<\/li>\n<li>Type <em>\u2018SetConnectionConfig.cs\u2019<\/em> in the <em>\u2018Name\u2019<\/em> textbox and click the <em>\u2018Ok\u2019<\/em> button<\/li>\n<\/ol>\n<\/li>\n<li>Add a reference to <em>&#8216;System.Web&#8217;<\/em> in the <em>&#8216;libPassword&#8217;<\/em> project\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018libPassword\u2019<\/em> project and click <em>\u2018Add\u2019<\/em>-&gt;<em>\u2019Reference\u2019 <\/em>in the context menu<\/li>\n<li>In the left side of the <em>\u2018Reference Manager\u2019<\/em> window, select <em>\u2018Assemblies\u2019<\/em>-&gt;<em>\u2019Framework\u2019<\/em><\/li>\n<li>In the <em>\u2018Reference Manager\u2019<\/em> window, click <em>\u2018System.Web\u2019<\/em> checkbox<\/li>\n<li>Click <em>\u2018Ok\u2019<\/em> button<\/li>\n<\/ol>\n<\/li>\n<li>Add the following lines in the top of <em>&#8216;SetConnectionConfig.cs&#8217;<\/em> file, just below the <em>&#8216;Using&#8217;<\/em>s:\n<pre class=\"theme:vs2012 lang:c# decode:true\">using System.Web;\r\n  using System.Web.Configuration;\r\n  using System.Configuration;<\/pre>\n<\/li>\n<li>Create the method <em>&#8216;SetConnection&#8217;<\/em> using the following code:\n<pre class=\"theme:vs2012 lang:c# decode:true\">        public static void SetConnection(string ConnectionStringName,\r\n  string ConnectionString)\r\n          {\r\n              Configuration config;\r\n              if (HttpRuntime.AppDomainAppId != null)\r\n              {\r\n                  config = WebConfigurationManager.OpenWebConfiguration(\"~\");\r\n              }\r\n              else\r\n              {\r\n     config = ConfigurationManager.OpenExeConfiguration(\r\n  ConfigurationUserLevel.None);\r\n              }\r\n     var connectionStringsSection = \r\n              (ConnectionStringsSection)config.GetSection(\r\n   \t\t\t\t\"connectionStrings\");\r\n              connectionStringsSection.ConnectionStrings[ConnectionStringName]\r\n  .ConnectionString = ConnectionString;\r\n              config.Save();\r\n              ConfigurationManager.RefreshSection(\"connectionStrings\");\r\n          }<\/pre>\n<h3>Part III: Intercepting and Identifying connection errors<\/h3>\n<p>From version 6 and beyond, Entity Framework can use an Execution Strategy to control some aspects of the execution of statements in the database server, such as the retry policy.<\/p>\n<p>When an error happens because of a password expiration, we can change the password and retry the query with the new password, making the retry policy a good centralized way to implement this solution, avoiding the need of error handling to deal with password problems all around the application.<\/p>\n<p>This is the biggest part of our solution, we will need several steps to complete this third part:<\/p>\n<ul>\n<li>Create the class for the Execution Strategy<\/li>\n<li>Create the methods to deal with the connection string.<\/li>\n<li>Create the main method to control the retry policy<\/li>\n<li>Apply the Execution Strategy<\/li>\n<\/ul>\n<h4>Creating the class for the Execution Strategy<\/h4>\n<p>Let&#8217;s continue our walk-through creating a new class for the Execution Strategy:<\/p>\n<\/li>\n<li>Create the class <em>&#8216;PasswordStrategy&#8217;<\/em>\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018libPassword\u2019<\/em> project and click <em>\u2018Add\u2019<\/em>-&gt;<em>\u2019Class\u2019<\/em> in the context menu<\/li>\n<li>Type <em>\u2018PasswordStrategy.cs\u2019<\/em> in the <em>\u2018Name\u2019<\/em> textbox and click the <em>\u2018Ok\u2019<\/em> button<\/li>\n<\/ol>\n<\/li>\n<li>Add the following lines in the top of <em>&#8216;PasswordStrategy.cs&#8217;<\/em> file, just below the <em>&#8216;Using&#8217;<\/em>s:\n<pre class=\"theme:vs2012 lang:c# decode:true\">using System;\r\n  using System.Configuration;\r\n  using System.Data.Entity.Core.EntityClient;\r\n  using System.Data.Entity;\r\n  using System.Data.SqlClient;\r\n  using System.Data.Entity.Infrastructure;<\/pre>\n<\/li>\n<li>Change the inheritance of <em>&#8216;PasswordStrategy&#8217;<\/em> class using the following code:\n<pre class=\"theme:vs2012 lang:c# decode:true\">    public class PasswordStrategy : DbExecutionStrategy\r\n      {\r\n      }<\/pre>\n<\/li>\n<li>Add the following constants, using the code below. These codes are the error number returned by SQL Server if the password have expired or if the administrator configured the login to change the password on the next logon.\n<pre class=\"theme:vs2012 lang:c# decode:true\">        const int PasswordExpired = 18487;\r\n          const int MustChangePassword = 18488;<\/pre>\n<\/li>\n<li>We need to create static properties in the <em>\u2018PasswordStrategy\u2019<\/em> class for the connection string name and the context. <em>\u2018PasswordStrategy\u2019<\/em> needs the connection string name to retrieve and save the connection to the config file and needs the context to refresh the connection string in the context, otherwise the context wouldn&#8217;t notice the change.\n<p>This is the code for these properties:<\/p>\n<pre class=\"theme:vs2012 lang:c# decode:true\">        [ThreadStatic]\r\n          private static string _ConnectionStringName;\r\n          public static string ConnectionStringName\r\n          {\r\n              get\r\n              {\r\n                  return _ConnectionStringName;\r\n              }\r\n              set\r\n              {\r\n                  _ConnectionStringName = value;\r\n              }\r\n          }\r\n          [ThreadStatic]\r\n          private static DbContext _Context;\r\n          public static DbContext Context\r\n          {\r\n              get\r\n              {\r\n                  return _Context;\r\n              }\r\n              set\r\n              {\r\n                  _Context = value;\r\n              }\r\n          }<\/pre>\n<\/li>\n<li>Create a property called <em>&#8216;ConStr&#8217;<\/em> to simplify the access to the <strong>connectionstring.<\/strong><br \/>\n<h4>The information and context lifecycle<\/h4>\n<p>The <em>\u2018PasswordStrategy\u2019<\/em> class needs the information from the entity context and the connection string. The lifecycle of these information, context and connection string, in this class and the lifecycle of the entity context in the application needs to be similar, otherwise the information will be wrong and nothing will work.<\/p>\n<p>The <strong>Static<\/strong> definition for the properties specify the lifecycle as a single value for the entire application execution, however, the <strong>ThreadStatic<\/strong> attribute changes this lifecycle for a thread, so each thread can have different values for these properties.<\/p>\n<p>The entity context can be used in several different ways. Some of them will be compatible with this lifecycle we are developing, whereas some of them will not and will require a different <em>\u2018PasswordStrategy\u2019<\/em> class.<\/p>\n<p>These are the uses of the entity context that are supported by this implementation:<\/p>\n<ul>\n<li><strong>The same context instantiated in each thread:<\/strong> This is the main way of using the entity context that this solution is built for.<\/li>\n<li><strong>Multiple contexts with different connection strings, in different threads<\/strong>: It doesn&#8217;t matter if the application has different contexts with different connection strings. As long as they are used in different threads, everything will be ok.<\/li>\n<li><strong>Singleton context in a desktop application:<\/strong> As long as the context and the instance of \u2018<em>PasswordStrategy\u2019<\/em> are in the same thread, there is no problem.<\/li>\n<\/ul>\n<p>There are some other possible ways of using the context that will not be supported by this class:<\/p>\n<ul>\n<li><strong>Singleton context in a web application:<\/strong> Because the <strong>ThreadStatic<\/strong> attribute the values of the properties will be lost.<\/li>\n<li><strong>Multiple contexts using different connection string in the same thread:<\/strong> This class can&#8217;t store information about multiple contexts<\/li>\n<li><strong>Multiple singleton contexts:<\/strong> Same problem, this class can&#8217;t store information about multiple contexts<\/li>\n<\/ul>\n<pre class=\"theme:vs2012 lang:c# decode:true\">        private string ConStr\r\n          {\r\n              get\r\n              {\r\n                      return ConfigurationManager.ConnectionStrings\r\n                          [ConnectionStringName]?.ConnectionString;\r\n              }\r\n          }<\/pre>\n<p>Pay heed to the following details in the code:<\/p>\n<ul>\n<li>For reading purposes, <strong>ConfigurationManager<\/strong> class can be used for both web applications and desktop applications.<\/li>\n<li>I&#8217;m using the new null operator created in C# 6.0 to check whether the connection string really exists.<\/li>\n<\/ul>\n<\/li>\n<li>I will create a static attribute, <em>&#8216;ChangingPassword&#8217;<\/em>, to control the execution of the password-changing process. This process needs to be executed only once: If the process is already executing, then we won&#8217;t start the execution a second time.\n<pre class=\"theme:vs2012 lang:c# decode:true\">private static bool ChangingPassword = false;<\/pre>\n<h4>Dealing with Entity Framework string<\/h4>\n<p>This sample application is using database first, so we have an Entity Framework connection string with the information about the <strong>EDMX<\/strong> and the SQL Server connection string is inside it.<\/p>\n<p>We need to extract the SQL Server connection string from the Entity Framework string, change the password and create a new Entity Framework string with the new password. We\u2019ll do this by creating two methods for these tasks: <em>\u2018ExtractString\u2019<\/em> and <em>\u2018BuildString\u2019<\/em>.<\/p>\n<\/li>\n<li>Create the method <em>\u2018ExtractString\u2019<\/em>:\n<pre class=\"theme:vs2012 lang:c# decode:true\">        private string ExtractSQLString(string ConnectionString)\r\n          {\r\n              var efbuilder = new EntityConnectionStringBuilder(ConnectionString);\r\n              return efbuilder.ProviderConnectionString;\r\n          }<\/pre>\n<p>This method receives an Entity Framework connection string and uses the <strong>EntityConnectionStringBuilder<\/strong> class to extract the provider connection string, in our case, a SQL Server connection string.<\/p>\n<\/li>\n<li>Create the method <em>\u2018BuildString\u2019<\/em>:\n<pre class=\"theme:vs2012 lang:c# decode:true\">        private string BuildEntityString(string ProviderString)\r\n          {\r\n              var efBuilder= new EntityConnectionStringBuilder(ConStr);\r\n              efBuilder.ProviderConnectionString = ProviderString;\r\n              return efBuilder.ConnectionString;\r\n          }<\/pre>\n<p>This method receives the provider string, reads the Entity Framework string from the config file using the <em>\u2018ConStr\u2019<\/em> property, then uses the <strong>EntityConnectionStringBuilder<\/strong> to change the provider string and finally returns the complete Entity Framework string.<\/p>\n<h4>Retry policy: The main method<\/h4>\n<p>Let&#8217;s continue our walk-through and build the main method of our <em>\u2018PasswordStrategy\u2019<\/em> class:<\/p>\n<\/li>\n<li>Override the method <em>\u2018ShouldRetryOn\u2019<\/em>:\n<pre class=\"theme:vs2012 lang:c# decode:true\">        protected override bool ShouldRetryOn(Exception exception)\r\n          {\r\n          }<\/pre>\n<\/li>\n<li>Create the initial checks about the exception. We need to check three possibilities:\n<ol type=\"a\">\n<li>If the exception isn&#8217;t a <strong>SQLException<\/strong>, we return false and no retry will be attempted.<\/li>\n<li>If the error number isn&#8217;t about the password, either that it is expired or required to change, no retry will be tried.<\/li>\n<li>If the variable <em>\u2018ChangingPassword\u2019<\/em> is true, and the changing is already happening, return false so the context will be refreshed.\n<pre class=\"theme:vs2012 lang:c# decode:true\">            if (!(exception is SqlException))\r\n                  return false;\r\n              var number = ((SqlException)exception).Number;\r\n              if ((number != PasswordExpired) &amp;&amp; (number != MustChangePassword))\r\n                  return false;\r\n              if (ChangingPassword)\r\n                  return false;<\/pre>\n<\/li>\n<\/ol>\n<\/li>\n<li>Change the password using the following code:\n<pre class=\"theme:vs2012 lang:c# decode:true\">            try\r\n              {\r\n                  ChangingPassword = true; \/* Starting the password change *\/\r\n                  if (string.IsNullOrEmpty(ConStr))\r\n                      return false;\r\n                  var provStr = ExtractSQLString(ConStr);\r\n                  var newPassword = System.Guid.NewGuid();\r\n                  provStr =\r\n                      SQLChangePassword.ChangePwd(provStr, newPassword.ToString());\r\n                  SetConnectionConfig.SetConnection(\r\n  ConnectionStringName, BuildEntityString(provStr));\r\n                  Context.Database.Connection.ConnectionString = provStr;\r\n              }\r\n              finally\r\n              {\r\n                  ChangingPassword = false; \/* Finishing the password change *\/\r\n              }\r\n              return true;<\/pre>\n<p>This code is implementing the following steps:<\/p>\n<ol type=\"a\">\n<li>Check if the connection string name is valid<\/li>\n<li>Extracts the provider string from Entity Framework connection string<\/li>\n<li>Create the new password. It will be a GUID.<\/li>\n<li>Change the password in SQL Server, creating a new provider string with the new password.<\/li>\n<li>Save the new connection string, taking care to build a new Entity Framework connection string with the new password.<\/li>\n<li>Refresh the context connection string<\/li>\n<li>Change the field <em>&#8216;ChangingPassword&#8217;<\/em> to<strong> false<\/strong> again<\/li>\n<li>Return <strong>true<\/strong>. The context will retry the execution, this time with the new password.<\/li>\n<\/ol>\n<h4>Applying the PasswordStrategy<\/h4>\n<p>Strategy classes, such as our <em>&#8216;PasswordStrategy&#8217;<\/em> class, aren&#8217;t applied directly to the entity context. We need to create a new class inheriting from <em>&#8216;DbConfiguration&#8217;<\/em> class inside the same project than our entity context. It&#8217;s like magic: The context will find the new <em>&#8216;DbConfiguration&#8217;<\/em> class in the project and will use it.<\/p>\n<p>In our solution, we also need to add some lines to the entity context constructor. Since we are using \u2018database first\u2019, this is a bit trickier, because the entire context code is re-created every time the T4 files are processed, deleting any customization we create.<\/p>\n<p>The solution to this problem is create the customization inside the T4 files, so every time the T4 are processed the re-created code will already include our customization.<\/p>\n<\/li>\n<li>Create a new class called <em>&#8216;PasswordConfiguration&#8217;<\/em> inside <em>\u2018libData\u2019<\/em> project.\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018libPassword\u2019<\/em> project and click <em>\u2018Add\u2019<\/em>-&gt;<em>\u2019Class\u2019<\/em> in the context menu<\/li>\n<li>Type <em>\u2018PasswordConfiguration.cs\u2019<\/em> in the <em>\u2018Name\u2019<\/em> textbox and click the <em>\u2018Ok\u2019<\/em> button<\/li>\n<\/ol>\n<\/li>\n<li>Add the following lines to the top of <em>&#8216;PasswordConfiguration.cs&#8217;<\/em> file, just below the <em>&#8216;Using&#8217;<\/em>s:\n<pre class=\"theme:vs2012 lang:c# decode:true\">using libPassword;\r\n  using System.Data.Entity;<\/pre>\n<\/li>\n<li>Implement the <em>&#8216;PasswordConfiguration&#8217;<\/em> class using the following code:\n<pre class=\"theme:vs2012 lang:c# decode:true\">    public class PasswordConfiguration : DbConfiguration\r\n      {\r\n          public PasswordConfiguration()\r\n          {\r\n              SetExecutionStrategy(\"System.Data.SqlClient\",\r\n                          () =&gt; new PasswordStrategy());\r\n          }\r\n      }<\/pre>\n<\/li>\n<li>Inside <em>&#8216;North.context.tt&#8217;<\/em> file, add the following <em>&#8216;Using&#8217;<\/em>:\n<pre class=\"theme:vs2012 lang:c# decode:true\">using libPassword;<\/pre>\n<\/li>\n<li>Inside <em>&#8216;North.context.tt&#8217;<\/em> file, add the following lines inside the context constructor:\n<pre class=\"theme:vs2012 lang:c# decode:true\">            PasswordStrategy.ConnectionStringName = \"NORTHEntities\";\r\n              PasswordStrategy.Contexto = this;<\/pre>\n<p>You can recognize the constructor by the call for the <em>&#8216;Base&#8217;<\/em> class with the connection string name as a parameter.<\/p>\n<h3>First test of the solution<\/h3>\n<p>The first test is very simple: Just execute the web application. You will see the list of customers as a result, meaning everything worked fine, the application was able to change the password.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"613\" height=\"348\" class=\"wp-image-72454\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-6.png\" \/><\/p>\n<p>You can check the <strong>web.config<\/strong> file and you will notice that the password has changed in the connection string, proving that everything went fine.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1371\" height=\"206\" class=\"wp-image-72455\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-7.png\" \/><\/p>\n<p>If anything went wrong, if you need to review the previous steps, you will probably need to correct the <strong>SQL Server<\/strong> login and ensure the <em>\u2018User must change the password at next login\u2019<\/em> attribute is set.<\/p>\n<h3>Publishing to Production<\/h3>\n<p>Our last step is the deployment to Production. There are several tools you can use to deploy the solution to Production. I will use web deployment in Visual Studio to illustrate how we can change the <strong>web.config<\/strong> file and encrypt the connection string during the deployment.<\/p>\n<p>It\u2019s important to keep in mind that this is only an example illustrating the potential of a process that hides the password from everyone. There are a many deployment solutions, and I\u2019m sure that I will not need to detail too much of the other possibilities in this article.<\/p>\n<p>There are some caveats in the publishing to Production:<\/p>\n<ul>\n<li>Our application needs the right to change the file with the new password. We will need to set ACL rights in the destination folders<\/li>\n<li>It\u2019s not safe to open write permissions in the root of our web application. The best solution will be to split our web config, storing our connection strings in a different folder and set the ACL only for this different folder<\/li>\n<li>Web Config Transformations, which are needed to change the connection string between environments, do not work with split <strong>web.config<\/strong> files. It\u2019s certainly possible to make it work, but it\u2019s too awkward, so the best solution will be a work-around.<\/li>\n<\/ul>\n<p>These are the deployment steps:<\/p>\n<ul>\n<li>Split the <strong>web.config<\/strong>, creating a different file for the connection string<\/li>\n<li>Configure Web.Config Transformations<\/li>\n<li>Create a publishing profile and configure encryption<\/li>\n<li>Configure the ACL in the publishing profile<\/li>\n<li>Publish the application<\/li>\n<\/ul>\n<h4>Web.Config Encryption and NLBS<\/h4>\n<p>Network Load Balancing Service, or NLBS, is a windows service used to create a pool of web servers with the same content, balancing the web request.<\/p>\n<p>It\u2019s important to notice the solution I\u2019m presenting here will require further configuration if your application is running in an NLBS environment, because all <strong>web.config<\/strong> files will need to use the same encryption key. You can read more about this <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/2w117ede(v=vs.100).aspx\">here<\/a>, but this is beyond the planned scope for this article.<\/p>\n<p>In fact, even besides the encryption, this solution will only work in a NLBS environment if you have some way to synchronize the <strong>web.config<\/strong> files across multiple servers. This is beyond this article.<\/p>\n<h3>Splitting the Web.Config<\/h3>\n<p>It\u2019s very simple: we create a new file in a different folder, move the connection strings to the new file and connect both. Let\u2019s do it:<\/p>\n<\/li>\n<li>Create a new folder called <em>\u2018Config\u2019<\/em>\n<ol type=\"a\">\n<li>In the <em>\u2018Solution Explorer\u2019<\/em> window, right-click <em>\u2018webCustomer\u2019<\/em> project and click <em>\u2018Add\u2019<\/em> -&gt; <em>\u2018New Folder\u2019<\/em> context menu item<\/li>\n<li>Type <em>\u2018Config\u2019<\/em> as the name of the new folder<\/li>\n<\/ol>\n<\/li>\n<li>Create a new file called <em>\u2018conn.config\u2019<\/em> inside the <em>\u2018Config\u2019<\/em> folder\n<ol type=\"a\">\n<li>Right-Click the <em>\u2018Config\u2019<\/em> folder, click <em>\u2018Add\u2019<\/em> -&gt; <em>\u2018New Item\u2019<\/em><\/li>\n<li>In the \u2018Add new item\u2019 window, select <em>\u2018Visual C#\u2019<\/em> -&gt; <em>\u2018Web\u2019<\/em> in the left side<\/li>\n<li>In the <em>\u2018Add new item\u2019<\/em> window, select <em>\u2018Web Configuration File\u2019<\/em> in the right side of the window<\/li>\n<li>Type <em>\u2018conn.config\u2019<\/em> in the \u2018Name\u2019 textbox and click <em>\u2018Add\u2019<\/em> button<\/li>\n<\/ol>\n<\/li>\n<li>Copy the <em>\u2018connectionString\u2019<\/em> element from the <em>\u2018web.config\u2019<\/em> to the <em>\u2018conn.config\u2019<\/em><\/li>\n<li>Change the <em>\u2018connectionString\u2019 <\/em>element in the <em>\u2018web.config\u2019<\/em> file to be as the following:\n<pre class=\"theme:vs2012 lang:c# decode:true\">&lt;connectionStrings configSource=\"Config\\conn.config\" \/&gt;<\/pre>\n<\/li>\n<\/ol>\n<h3>Configure Web.Config Transformations<\/h3>\n<p><strong>\u2018Web.Config<\/strong> transformations\u2019 is a feature that allows us to replace pieces of the <strong>web.config<\/strong> file, such as connection string, during the build and deployment process.<\/p>\n<p>Besides the <strong>web.config<\/strong> file in your project, you also have an additional <strong>web.config <\/strong>file for each solution configuration and you can see these files in <strong>Solution Explorer<\/strong> window, by expanding <strong>web.config<\/strong> file. The file names are <strong>web.debug.config<\/strong> and <strong>web.realease.config<\/strong>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"189\" height=\"62\" class=\"wp-image-72456\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-8.png\" \/><\/p>\n<p>Usually we could do some changes to <strong>Web.Release.Config<\/strong> file to transform our connection string from Development to Production. However, <strong>web.config<\/strong> transformations don\u2019t work by default with split <strong>web.config<\/strong> files. We could configure a custom build task to transform the <em>\u2018conn.config\u2019<\/em> file, but it will be much easier to just configure a transformation for the <em>\u2018configSource\u2019<\/em> attribute, making the main <strong>web.config<\/strong> point to a different file in Production.<\/p>\n<p>These are the steps we need to do:<\/p>\n<ol>\n<li>In the \u2018Solution Explorer\u2019 window, below the <em>\u2018Config\u2019<\/em> folder, right-click the <em>\u2018conn.config\u2019<\/em> file and click <em>\u2018Copy\u2019 <\/em>in the context menu<\/li>\n<li>Right-Click the <em>\u2018Config\u2019<\/em> folder and click <em>\u2018Paste\u2019<\/em> in the context menu<\/li>\n<li>Rename the new file <em>\u2018conn \u2013 Copy.config\u2019<\/em> to <em>\u2018conn.Release.config\u2019<\/em><\/li>\n<li>Copy the entire <em>\u2018connectionString\u2019<\/em> element from the <em>\u2018conn.config\u2019<\/em> file to the <em>\u2018conn.Release.config\u2019<\/em>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"169\" height=\"53\" class=\"wp-image-72457\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-9.png\" \/><\/p>\n<\/li>\n<li>Double-click the <em>\u2018conn.Release.config\u2019 <\/em>file to open it<\/li>\n<li>Change the <em>\u2018User Id\u2019 <\/em>in the connection string from <em>\u2018usrQuality\u2019 <\/em>to <em>\u2018usrProduction\u2019<\/em><\/li>\n<li>Open the <strong>Web.Release.Config<\/strong> file in the root of the project<\/li>\n<li>Add the following tag just above the <strong>system.web<\/strong> element:\n<pre class=\"theme:vs2012 lang:c# decode:true\">  &lt;connectionStrings configSource=\"Config\\conn.Release.config\" xdt:Transform=\"SetAttributes\" \/&gt;<\/pre>\n<\/li>\n<\/ol>\n<p>Pay heed to the attributes <strong>xdt:Transform<\/strong>. It\u2019s responsible for the transformation, indicating how the tag will be transformed. In our example, the tags will be transformed by setting attributes, <em>\u2018configSource\u2019<\/em> attribute in our example.<\/p>\n<h3>Create a publishing profile and configure encryption<\/h3>\n<p>The publishing profile is created when we publish our web application. However, we need to do a small change to the publishing profile and we can\u2019t do this change through the publish wizard.<\/p>\n<p>We will solve this \u2018chicken and egg\u2019 puzzle by executing the publishing wizard, cancelling the wizard before finishing, changing the publishing profile and executing the publishing wizard again, this time deploying the application.<\/p>\n<p>Let\u2019s do a walk-through to complete these steps:<\/p>\n<ol>\n<li>In Solution Explorer window, right-click <em>\u2018webCustomer\u2019<\/em> project and click <em>\u2018Publish\u2026\u2019<\/em> context menu item\n<p><img loading=\"lazy\" decoding=\"async\" width=\"519\" height=\"464\" class=\"wp-image-72458\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-10.png\" \/><\/p>\n<\/li>\n<li>In <em>\u2018Publish Web\u2019<\/em> window, click <em>\u2018Custom\u2019<\/em> button<\/li>\n<li>In <em>\u2018New Custom Profile\u2019<\/em> window, in <em>\u2018Profile Name\u2019<\/em> textbox, type <em>\u2018Production\u2019 <\/em>and click <em>\u2018Ok\u2019<\/em> button\n<p><img loading=\"lazy\" decoding=\"async\" width=\"718\" height=\"562\" class=\"wp-image-72459\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-11.png\" \/><\/p>\n<\/li>\n<li>Click <em>\u2018Next\u2019<\/em> button to move to <em>\u2018Connection\u2019<\/em> page in the wizard<\/li>\n<li>In the <em>\u2018Connection\u2019<\/em> page, select <em>\u2018Web Deploy\u2019 <\/em>in the <em>\u2018Publishing Method\u2019<\/em> drop down<\/li>\n<li>In the <em>\u2018Connection\u2019<\/em> page, type <em>\u2018Localhost\u2019<\/em> in the <em>\u2018Server\u2019<\/em> textbox<\/li>\n<li>In the <em>\u2018Connection\u2019<\/em> page, type <em>\u2018Default Web Site\/webCustomers\u2019<\/em> in the <em>\u2018Site Name\u2019<\/em> textbox<\/li>\n<li>In the <em>\u2018Connection\u2019<\/em> page, type <em>\u2018http:\/\/localhost\/webCustomers\u2019<\/em> in the <em>\u2018Destination Url\u2019<\/em> page\n<p><img loading=\"lazy\" decoding=\"async\" width=\"716\" height=\"563\" class=\"wp-image-72460\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-12.png\" \/><\/p>\n<\/li>\n<li>Click <em>\u2018Next\u2019<\/em> button<\/li>\n<li>In the \u2018Settings\u2019 page, click \u2018Next\u2019 button.<\/li>\n<li>In the <em>\u2018Preview\u2019<\/em> page, click <em>\u2018Close\u2019<\/em> button<\/li>\n<li>In <em>\u2018Solution Explorer\u2019<\/em> window, below <em>\u2018webCustomers\u2019<\/em> project, expand <em>\u2018Properties\u2019<\/em>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"278\" height=\"285\" class=\"wp-image-72461\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-13.png\" \/><\/p>\n<\/li>\n<li>Double-click <em>\u2018Production.pubxml\u2019<\/em> file to open it<\/li>\n<li>Insert the following tag below <em>\u2018&lt;\/PropertyGroup&gt;\u2019<\/em> tag:\n<pre class=\"theme:vs2012 lang:c# decode:true\">      &lt;Target Name=\"CustomPostPublishActions\" AfterTargets=\"MSDeployPublish\"&gt;\r\n      \t\t&lt;Exec \r\n  Command=\"C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\aspnet_regiis -pe connectionStrings -app \/webCustomers\" \/&gt;\r\n    &lt;\/Target&gt;<\/pre>\n<\/li>\n<\/ol>\n<p>Pay heed to the following details:<\/p>\n<ul>\n<li>The <strong>AfterTargets<\/strong> attribute determine when the task will be executed<\/li>\n<li>The <strong>Exec<\/strong> element is responsible for the execution<\/li>\n<li>Although there are other configurations to encrypt the <em>\u2018connectionString\u2019<\/em> element, this is the only one that will work with a split <strong>web.config<\/strong> file<\/li>\n<\/ul>\n<h3>Configure the ACL in the publishing profile<\/h3>\n<p>We need to add permissions to the web site to change the file inside the <em>\u2018Config\u2019<\/em> folder. We can just include the following configuration to the <em>\u2018Production.pubxml\u2019<\/em> file, just below the previous <em>\u2018Target\u2019<\/em> element we included:<\/p>\n<pre class=\"theme:vs2012 lang:c# decode:true\">  &lt;Target Name=\"SetupCustomAcls\" AfterTargets=\"AddIisSettingAndFileContentsToSourceManifest\"&gt;\r\n      &lt;ItemGroup&gt;\r\n        &lt;MsDeploySourceManifest Include=\"setAcl\"&gt;\r\n          &lt;Path&gt;$(_MSDeployDirPath_FullPath)\\Config&lt;\/Path&gt;\r\n          &lt;setAclAccess&gt;Read,Write,Modify&lt;\/setAclAccess&gt;\r\n          &lt;setAclResourceType&gt;Directory&lt;\/setAclResourceType&gt;\r\n          &lt;AdditionalProviderSettings&gt;setAclResourceType;setAclAccess&lt;\/AdditionalProviderSettings&gt;\r\n        &lt;\/MsDeploySourceManifest&gt;\r\n      &lt;\/ItemGroup&gt;\r\n    &lt;\/Target&gt;\r\n    &lt;Target Name=\"DeclareCustomParameters\" AfterTargets=\"AddIisAndContentDeclareParametersItems\"&gt;\r\n      &lt;ItemGroup&gt;\r\n        &lt;MsDeployDeclareParameters Include=\"SetAclParam\"&gt;\r\n          &lt;Kind&gt;ProviderPath&lt;\/Kind&gt;\r\n          &lt;Scope&gt;setAcl&lt;\/Scope&gt;\r\n          &lt;Match&gt;^$(_EscapeRegEx_MSDeployDirPath)\\\\Config$&lt;\/Match&gt;\r\n          &lt;Description&gt;Add write permission to the App_Data folder.&lt;\/Description&gt;\r\n          &lt;DefaultValue&gt;{$(_MsDeployParameterNameForContentPath)}\/Config&lt;\/DefaultValue&gt;\r\n          &lt;Value&gt;$(_DestinationContentPath)\/Config&lt;\/Value&gt;\r\n          &lt;Tags&gt;Hidden&lt;\/Tags&gt;\r\n          &lt;Priority&gt;$(VsSetAclPriority)&lt;\/Priority&gt;\r\n          &lt;ExcludeFromSetParameter&gt;True&lt;\/ExcludeFromSetParameter&gt;\r\n        &lt;\/MsDeployDeclareParameters&gt;\r\n      &lt;\/ItemGroup&gt;\r\n    &lt;\/Target&gt;<\/pre>\n<p>The web deployment process creates a manifest for the application and executes the manifest during the deployment. We can only see the manifest when we publish the application to a deployment package instead directly to the server.<\/p>\n<p>The first <em>\u2018Target\u2019<\/em> element is defining a <em>\u2018setAcl\u2019<\/em> action inside the manifest. The second <em>\u2018Target\u2019<\/em> element is parameterizing the action, so the deployment process will be able to deal with the path when the application is deployed to different servers.<\/p>\n<h3>Publish the application<\/h3>\n<p>After configuring everything, publish the application is very easy:<\/p>\n<ol>\n<li>In <em>\u2018Solution Explorer\u2019<\/em> window, right-click the <em>\u2018webCustomer\u2019<\/em> project and click <em>\u2018Publish\u2026\u2019<\/em> context menu item<\/li>\n<li>In the <em>\u2018Publish Web\u2019<\/em> window, click <em>\u2018Publish\u2019 <\/em>button<\/li>\n<\/ol>\n<p>Once again, if everything is done correctly, you will see the web browser with the list of customers.<\/p>\n<p>You can open the <em>\u2018conn.release.config\u2019 <\/em>file in the <em>\u2018C:\\inetpub\\wwwroot\\webCustomers\\Config\u2019<\/em> folder and you will see something similar to the image below.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1026\" height=\"506\" class=\"wp-image-72462\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2017\/09\/word-image-14.png\" \/><\/p>\n<h2><strong>Conclusion<\/strong><\/h2>\n<p>The solution proposed in this article is able to greatly increase the security of your application environment by ensuring that access control conforms to a stringent policy. The higher security is not only because nobody knows the password but also because the administrator can enforce standard password policies to all application accounts instead of having to compromise by treating them as exceptions, using the attribute <em>\u2018Password Never Expires\u2019<\/em>.<\/p>\n<p>SQL Server will follow the password expiration policy and the application will change its password from time to time, ensuring a good password security.<\/p>\n<p>Another increase in security is the fact that this solution only works if every application has its own login. If two applications share the same login, the solution will not work.<\/p>\n<p>You can download the solution and contribute to it here: <a href=\"https:\/\/github.com\/DennesTorres\/ChangePassword\">https:\/\/github.com\/DennesTorres\/ChangePassword<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>How can you ensure that passwords conform to a policy, even if they are used for connecting applications to databases? Absolving them from the policy is a security risk and you don&#8217;t want to trouble the users with password changes. Dennes Torres shows how to manage application users\u2019 passwords in Entity Framework; so that no one, not even the database and IT administrators, knows the current  password.&hellip;<\/p>\n","protected":false},"author":50808,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538],"tags":[],"coauthors":[6810],"class_list":["post-72447","post","type-post","status-publish","format-standard","hentry","category-dotnet-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/72447","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/50808"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=72447"}],"version-history":[{"count":8,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/72447\/revisions"}],"predecessor-version":[{"id":72544,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/72447\/revisions\/72544"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=72447"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=72447"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=72447"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=72447"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}