views:

1136

answers:

3

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 IIdentity ?

Or is this unpossible?

A: 

I found some discussion here which may apply:

http://www.bokebb.com/dev/english/2047/posts/204721301.shtml

Hope this helps!

Adam

Adam Alexander
A: 

Yes, using impersonation.

dove
Can you elaborate? If MyThread was already running, can we change it's CurrentPrincipal?
Duncan
yes, did you follow the link? there are examples there.
dove
+3  A: 

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(
                identity,
                new string[] { "Role1", "Roll2" }
                );

        //...

        if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Roll1"))
        {
            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 director or site you are running in.

Martin Brown