AppDomain::SetThreadPrincipal Method (IPrincipal^)

 

Sets the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

public:
[SecurityPermissionAttribute(SecurityAction::Demand, Flags = SecurityPermissionFlag::ControlPrincipal)]
virtual void SetThreadPrincipal(
	IPrincipal^ principal
) sealed

Parameters

principal
Type: System.Security.Principal::IPrincipal^

The principal object to attach to threads.

Exception Condition
ArgumentNullException

principal is null.

PolicyException

The thread principal has already been set.

AppDomainUnloadedException

The operation is attempted on an unloaded application domain.

The following example shows the effect of using the SetThreadPrincipal method to change the principal that is available for attaching to threads that are executing in the application domain. It also shows the effect on threads of using the SetPrincipalPolicy method to change the principal policy of the application domain.

using namespace System;
using namespace System::Security::Principal;
using namespace System::Threading;
ref class ADPrincipal
{
public:
   static void PrintPrincipalInformation()
   {
      IPrincipal^ curPrincipal = Thread::CurrentPrincipal;
      if ( curPrincipal != nullptr )
      {
         Console::WriteLine( "Type: {0}", curPrincipal->GetType()->Name );
         Console::WriteLine( "Name: {0}", curPrincipal->Identity->Name );
         Console::WriteLine( "Authenticated: {0}", curPrincipal->Identity->IsAuthenticated );
         Console::WriteLine();
      }
   }

};

int main()
{

   // Create a new thread with a generic principal.
   Thread^ t = gcnew Thread( gcnew ThreadStart( ADPrincipal::PrintPrincipalInformation ) );
   t->Start();
   t->Join();

   // Set the principal policy to WindowsPrincipal.
   AppDomain^ currentDomain = AppDomain::CurrentDomain;
   currentDomain->SetPrincipalPolicy( PrincipalPolicy::WindowsPrincipal );

   // The new thread will have a Windows principal representing the
   // current user.
   t = gcnew Thread( gcnew ThreadStart( ADPrincipal::PrintPrincipalInformation ) );
   t->Start();
   t->Join();

   // Create a principal to use for new threads.
   IIdentity^ identity = gcnew GenericIdentity( "NewUser" );
   IPrincipal^ principal = gcnew GenericPrincipal( identity,nullptr );
   currentDomain->SetThreadPrincipal( principal );

   // Create a new thread with the principal created above.
   t = gcnew Thread( gcnew ThreadStart( ADPrincipal::PrintPrincipalInformation ) );
   t->Start();
   t->Join();

   // Wait for user input before terminating.
   Console::ReadLine();
}

SecurityPermission

for ability to manipulate the principal object. Associated enumeration: SecurityPermissionFlag::ControlPrincipal. Security action: Demand.

.NET Framework
Available since 1.1
Return to top
Show: