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 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( _  
  2. With the policy set, use the static 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)   
  3. When the principal object has been created, you can use one of several methods to validate it.

To create a WindowsPrincipal object for a single validation

  1. Initialize a new WindowsIdentity object by calling the static 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.

See also