Export (0) Print
Expand All

How to: Refuse Permissions by Using the RequestRefuse Flag

If you are concerned that your code might be used to access system resources maliciously, you can request that it never be granted a particular permission. For example, an application that browses data in a file but never modifies the data might refuse any file-write permissions. In the event of a bug or a malicious attack, this code cannot damage the data on which it operates.

RequestRefuse allows a large set of permissions to be requested as optional permissions, while ensuring that certain specific permissions are not in the grant.

The following example uses RequestRefuse to refuse FileIOPermission from the common language runtime security system:

//The request is placed at the assembly level. 
using System.Security.Permissions;
[assembly:FileIOPermission(SecurityAction.RequestRefuse ,Unrestricted = true)]

namespace MyNameSpace
{
   using System;
   using System.Security;
   using System.Security.Permissions;
   using System.IO;

   public class MyClass
   {
      public MyClass()
     {       
     }
      
      public static int Main(string[] args)
      {
         //Creation of the log is attempted in the try block.
         try
         {   
            StreamWriter TextStream = new StreamWriter("Log.txt");
            TextStream.WriteLine("This Log was created on {0}", DateTime.Now);
            TextStream.Close();
            Console.WriteLine("The Log was created");
         }
         //Catch the Security exception and inform the user that the 
         //application was not granted FileIOPermission.
         catch(SecurityException)
        {
            Console.WriteLine("This application does not have permission to write to the disk.");
        }
      

         return 0;
      }
   }
}    

The previous example is not granted permission to create the file and generates a security exception. The catch statement intercepts the exception and the application displays the following message to the console:

This application does not have permission to write to the disk.

Community Additions

ADD
Show:
© 2014 Microsoft