Temporarily re-enabling CAS policy during migration

Over the last few weeks we’ve been looking at the changes to security policy in .NET 4, namely that security policy is now in the hands of the host and the operating system.

While we’ve looked at how to update code that implicitly uses CAS policy, loads assemblies from remote sources, and explicitly uses CAS policy, in applications of larger size it may not be practical to update all the code at once.  Similarly, you might be able to update the code in your application, but may rely on a third party assembly that is not yet updated for the changes in CAS policy.

If you do find yourself needing to re-enable CAS policy temporarily, in order to move a large code base to the new v4 security APIs bit by bit rather than all at once, or to use an assembly that you don’t control, there is a configuration switch that you can set in order to flip your process back into legacy CAS policy mode.

In order to temporarily enable legacy CAS policy in your process, you’ll need an .exe.config file for your application with the legacy security policy switch set in its runtime section.  So, if your application’s entry point is YourApp.exe, you’ll have next to it a YourApp.exe.config file.  (You can also use the app.config feature in your Visual Studio project).  The file should look like this for any release of the .NET Framework v4 after beta 1:

 <configuration>  <runtime>    <NetFx40_LegacySecurityPolicy enabled="true" />  </runtime></configuration>

In .NET 4 Beta 1, the switch has a slightly different name:

 <configuration>  <runtime>    <legacyCasPolicy enabled="true" />  </runtime></configuration>

One thing to note is that this switch must be set on the process-level.  So, if you’re using a third party control that uses CAS policy, you may well need to set the switch for both Visual Studio in devenv.exe.config and for your application itself.  That way the control will work both in the Visual Studio process during your development, as well as in your process at runtime.