Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

How to: Perform Imperative Security Checks

For an imperative demand, you can call the Demand method of the PrincipalPermission object to determine whether the current principal object represents the specified identity, role, or both. Assuming a properly constructed PrincipalPermission object called MyPrincipalPermission, an imperative demand can be called with the following code.

MyPrincipalPermission.Demand();

The following code example uses an imperative check to ensure that a GenericPrincipal matches the PrincipalPermission object. An imperative check is useful when many methods or other assemblies in the application domain must make role-based determinations. While this example is extremely simple, it illustrates the behavior associated with a role-based demand.

using System;
using System.Security.Permissions;
using System.Security.Principal;
using System.Security;
using System.Threading;
using System.Security.Cryptography;

public class MainClass
{
    public static int Main(string[] args)
    {
        Console.WriteLine("Enter '1' to use the proper identity or " +
            "any other character to use the improper identity.");

        if(Console.ReadLine() == "1")
        {
            // Create a generic identity.
            GenericIdentity MyIdentity = new GenericIdentity("MyUser");

            // Create a generic principal.
            String[] MyString = {"Administrator", "User"};

            GenericPrincipal MyPrincipal = 
                new GenericPrincipal(MyIdentity, MyString);

            Thread.CurrentPrincipal = MyPrincipal;
        }

        PrivateInfo();
        return 0;
    }

    public static void PrivateInfo()
    {
        try
        {
            // Create a PrincipalPermission object.
            PrincipalPermission MyPermission = 
                new PrincipalPermission("MyUser", "Administrator");

            // Demand this permission.
            MyPermission.Demand();

            // Print secret data.
            Console.WriteLine(
                "\n\nYou have access to the private data!");
        }
        catch(SecurityException e) 
        {
            Console.WriteLine(e.Message);
        }
    }
}

If the user types 1, the principal and identity objects needed to access the PrivateInfo method are created. If the user types any other character, no principal and identity objects are created and a security exception is thrown when the PrivateInfo method is called. If the current thread is associated with a principal that has the name MyUser and the Administrator role, the following message appears.

You have access to the private data!
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.