In C#, how do I set the Identity of a Thread?
For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?
Or is this not possible?
In C#, how do I set the Identity of a Thread?
For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?
Or is this not possible?
Update for the accepted answer [apply ONLY on .NET framework 4.5 and above]
In
.NET 4.5
the propertyIsAuthenticated
has no set accessor, so you can not set it directly as the accepted answer doing.You can use the following code for setting that property.
You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits from System.Security.Principal.IIdentity, but you need a class that inherits from System.Security.Principal.IPrincipal that takes the type of Identity you are using.
For simplicity sake the .Net framework provides GenericPrincipal and GenericIdentity classes which can be used like this:
This won't however give you windows rights to stuff using the new identity. But it can be useful if you are developing a web site and want to create your own user management.
If you want to pretend to be a different Windows user than the account you are currently using then you need to use impersonation. An example of how to do this can be found in the Help for System.Security.Principal.WindowsIdentity.Impersonate(). There are limitations about which accounts the account you are running under can impersonate.
In some cases the .Net framework does impersonation for you. One example of where this occurs is if you are developing a ASP.Net web site and you have Integrated Windows Authentication switched on for the virtual directory or site you are running in.
Yes, using impersonation literally
and the class is as follows, for settings I use castle dictionary adaptor if it looks strange.