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.
Assembly: mscorlib (in mscorlib.dll)
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)] public void SetThreadPrincipal( IPrincipal principal )
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 System; using System.Security.Principal; using System.Threading; class ADPrincipal { static void Main(string[] args) { // Create a new thread with a generic principal. Thread t = new Thread(new ThreadStart(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 = new Thread(new ThreadStart(PrintPrincipalInformation)); t.Start(); t.Join(); // Create a principal to use for new threads. IIdentity identity = new GenericIdentity("NewUser"); IPrincipal principal = new GenericPrincipal(identity, null); currentDomain.SetThreadPrincipal(principal); // Create a new thread with the principal created above. t = new Thread(new ThreadStart(PrintPrincipalInformation)); t.Start(); t.Join(); // Wait for user input before terminating. Console.ReadLine(); } static void PrintPrincipalInformation() { IPrincipal curPrincipal = Thread.CurrentPrincipal; if(curPrincipal != null) { Console.WriteLine("Type: " + curPrincipal.GetType().Name); Console.WriteLine("Name: " + curPrincipal.Identity.Name); Console.WriteLine("Authenticated: " + curPrincipal.Identity.IsAuthenticated); Console.WriteLine(); } } }
for ability to manipulate the principal object. Associated enumeration: SecurityPermissionFlag.ControlPrincipal. Security action: Demand.
Available since 1.1