Set Identity of Thread
Update for the accepted answer [apply ONLY on .NET framework 4.5 and above]
In .NET 4.5
the property IsAuthenticated
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.
GenericIdentity identity = new GenericIdentity("someuser", "Forms");
Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[] { "somerole" });
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:
using System.Security.Principal;
// ...
GenericIdentity identity = new GenericIdentity("M.Brown");
identity.IsAuthenticated = true;
// ...
System.Threading.Thread.CurrentPrincipal =
new GenericPrincipal(
identity,
new string[] { "Role1", "Role2" }
);
//...
if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Role1"))
{
Console.WriteLine("Permission denied");
return;
}
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.