Duncan Duncan - 1 year ago 113
C# Question

Set Identity of Thread

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?

Answer Source

You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits off System.Principal.IIdentity, but you need a class that inherits off System.Principal.IPrincipal that takes the type of Identity you are using. For simplicity sake the .Net framework provides GenericPrincipal and GenericIdentity 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(
                new string[] { "Role1", "Roll2" }


        if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Roll1"))
            Console.WriteLine("Permission denied");

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download