13.7 Determine at Run Time if Your Code Has a Specific Permission


13.7 Determine at Run Time if Your Code Has a Specific Permission

Problem

You need to determine at run time if your assembly has a specific permission.

Solution

Instantiate and configure the permission you want to test for and then pass it as an argument to the static method IsGranted of the class System.Security.SecurityManager .

Discussion

Using minimum permission requests , you can ensure that the runtime grants your assembly a specified set of permissions; if your code is running, you can safely assume that it has the requested minimum permissions. However, you might want to implement opportunistic functionality that your application offers only if the runtime grants your assembly appropriate permissions. This approach is partially formalized using optional permission requests, which allow you to define a set of permissions that your code could make use of if security policy granted them, but which are not essential for the successful operation of your code. (Recipe 13.5 provides more detail on using optional permission requests.)

The problem with optional permission requests is that the runtime has no ability to communicate to your assembly which of the requested optional permissions it has granted. You can try to use a protected operation and fail gracefully if the call results in the exception System.Security.SecurityException . However, it's more efficient to determine in advance if you have the necessary permissions. You can then build logic into your code to avoid invoking protected members that will cause stack walks and raise security exceptions. The following code fragment shows how to use the IsGranted method to determine if the current assembly has write permission to the directory C:\Data. You could make such a call each time you needed to test for the permission, but it's more efficient to use the returned Boolean value to set a configuration flag indicating whether to allow users to save files.

 // Define a variable to indicate whether the assembly has write access // to the C:\Data folder. bool canWrite = false;          // Create and configure a FileIOPermission object that represents write  // access to the C:\Data folder. System.Security.Permissions.FileIOPermission fileIOPerm =      new System.Security.Permissions.FileIOPermission(     System.Security.Permissions.FileIOPermissionAccess.Write, @"C:\Data");                  // Test if the current assembly has the specified permission. canWrite = System.Security.SecurityManager.IsGranted(fileIOPerm); 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net