Export (0) Print
Expand All

Adding Imperative Security Checks to Components

Visual Studio .NET 2003

Imperative security checks allow you to protect specific blocks of code by requiring appropriate permissions. You can use permission objects to add imperative security checks to your code. A permission object is an instance of a specialized class that represents a particular type of permission. For example, the FileIOPermission class represents the right to read, append, or write files or directories. You add an imperative security check by creating an instance of the appropriate security object, and then calling that object's Demand function. This has the effect of denying access to all callers except those that have the appropriate permission. If a caller does not have the appropriate permissions to execute a called block of code, a SecurityException is thrown. For this reason, you should always consider how you want to handle a potential security exception. For details, see Handling Exceptions in Your Component.

To add an imperative security check to your component

  1. Determine the kind of security permission that is needed to protect your code. For example, if your code involves using the file system, you would choose FileIOPermission. For details on types of code-access permissions, see Code Access Permissions.
  2. Decide how you will handle a SecurityException if thrown. If you choose to handle it in your component, you should enclose your protected code within a Try...Catch...Finally block (try...catch...finally in C#), with appropriate code to handle the exception in the Catch block. For details, see Handling Exceptions in Your Component.
  3. Create an instance of the appropriate permission object immediately preceding the code you want to protect.
    Note   Your permission object might require parameters when instanced. For details about which parameters are required, see the .NET Framework reference topic for the specific class.
    ' Visual Basic
    Dim MyPermission as New _
    // C#
    System.Security.Permissions.FileIOPermission MyPermission = new 
  4. Call the Demand method of your permission object. This will require any calling methods to demonstrate the appropriate permissions in order to execute the protected code. This will throw an exception if permission is not granted, so you may want to enclose this statement within structured exception handling.
    ' Visual Basic
    Catch e as Exception
       ' Insert code to handle the exception.
    End Try
    // C#
    catch (Exception e)
       // Insert code to handle the exception.

See Also

Code Security and Signing in Components | Adding Security Attributes to Components | Security Tutorial | Key Security Concepts

© 2014 Microsoft