如何:通过使用 RequestRefuse 标志拒绝授予权限

更新:2007 年 11 月

如果担心您的代码会被恶意地用来访问系统资源,则可以请求永远不向它授予相应的权限。例如,浏览文件中的数据但从不修改数据的应用程序可能拒绝任何文件写入权限。在发生 bug 或恶意攻击时,此代码不会损坏它操作的数据。

RequestRefuse 允许将大量权限作为可选的权限来请求,同时确保某些特定的权限不在授予之列。

下面的示例使用 RequestRefuse 来拒绝来自公共语言运行库安全系统的 FileIOPermission

示例

Imports System
Imports System.IO
Imports System.Security
Imports System.Security.Permissions
'The request is placed at the assembly level. 
<assembly: FileIOPermission(SecurityAction.RequestRefuse, Unrestricted := True)>

Namespace MyNameSpace
   Public Class MyClass1
      Public Sub New()
      End Sub
      
      Public Shared Sub Main()
         'Creation of the log is attempted in the try block.
         Try
            Dim TextStream As 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
            Console.WriteLine("This application does not have permission to write to the disk.")         
         End Try
      End Sub
   End Class
End Namespace
//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;
      }
   }
}    

上面的示例没有被授予创建文件的权限,将生成安全性异常。捕捉语句截获异常,同时应用程序将下面的消息显示到控制台上:

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

请参见

概念

请求权限

其他资源

利用属性扩展元数据

代码访问安全性