Compartir a través de


How to: Create a WindowsPrincipal Object 

There are two ways to create a WindowsPrincipal object, depending on whether code must repeatedly perform role-based validation or must perform it only once.

If code must repeatedly perform role-based validation, the first of the following procedures produces less overhead. When code needs to make role-based validations only once, you can create a WindowsPrincipal object by using the second of the following procedures.

To create a WindowsPrincipal object for repeated validation

  1. Call the SetPrincipalPolicy method on the AppDomain object that is returned by the static System.AppDomain.CurrentDomain property, passing the method a PrincipalPolicy enumeration value that indicates what the new policy should be. Supported values are NoPrincipal, UnauthenticatedPrincipal, and WindowsPrincipal. The following code demonstrates this method call.

    AppDomain.CurrentDomain.SetPrincipalPolicy(
        PrincipalPolicy.WindowsPrincipal);
    
    AppDomain.CurrentDomain.SetPrincipalPolicy( _
        PrincipalPolicy.WindowsPrincipal)
    
  2. With the policy set, use the static System.Threading.Thread.CurrentPrincipal property to retrieve the principal that encapsulates the current Windows user. Because the property return type is IPrincipal, you must cast the result to a WindowsPrincipal type. The following code initializes a new WindowsPrincipal object to the value of the principal associated with the current thread.

    WindowsPrincipal MyPrincipal = 
        (WindowsPrincipal) Thread.CurrentPrincipal;
    
    Dim MyPrincipal As WindowsPrincipal = _
        CType(Thread.CurrentPrincipal, WindowsPrincipal) 
    

To create a WindowsPrincipal object for a single validation

  1. Initialize a new WindowsIdentity object by calling the static System.Security.Principal.WindowsIdentity.GetCurrent method, which queries the current Windows account and places information about that account into the newly created identity object. The following code creates a new WindowsIdentity object and initializes it to the current authenticated user.

    WindowsIdentity MyIdentity = WindowsIdentity.GetCurrent();
    
    Dim MyIdentity As WindowsIdentity = WindowsIdentity.GetCurrent()
    
  2. Create a new WindowsPrincipal object and pass it the value of the WindowsIdentity object created in the preceding step.

    WindowsPrincipal MyPrincipal = new WindowsPrincipal(MyIdentity);
    
    Dim MyPrincipal As New WindowsPrincipal(MyIdentity)
    
  3. When the principal object has been created, you can use one of several methods to validate it. For more information, see Role-Based Security Checks.

See Also

Concepts

Principal and Identity Objects