Search code examples
c#impersonationwindows-identityidentity-delegation

Change the context of a thread to other user


A user triggers a event, thus the thread is in the context of said user. I iterate over all connected users and want to send them this event, but I want to use classic Authorization to determine if they should receive the event. Problem is the thread principal etc is in the context of the user that triggered the event.

I'm looking into impersonate the thread and then do the authorization. I found this article on it

http://msdn.microsoft.com/en-us/library/ff647248.aspx#ImpersonationDelegation5

using System.Security.Principal;
…
WindowsIdentity wi = new WindowsIdentity(userName@fullyqualifieddomainName);
WindowsImpersonationContext ctx = null;

try
{
  ctx = wi.Impersonate();
  // Thread is now impersonating you can call the backend operations here...

catch
{
  // Prevent exceptions propagating.
}
finally
{
  // Ensure impersonation is reverted
  ctx.Undo();
}

After ctx = wi.Impersonate(); the thread is still in the context of the calling user, what am I doing wrong?

update I want to run this code as the other user

provider = AuthorizationFactory.GetAuthorizationProvider();
provider.Authorize(Thread.CurrentPrincipal, Rule)

A little blogpost i did that covers the steps needed http://andersmalmgren.com/2014/06/12/client-server-event-aggregation-with-role-authorization/


Solution

  • provider.Authorize(principal, context) has System.Security.Principal.IPrincipal as its first paramter (see msdn). Why not create a System.Security.Principal.WindowsPrincipal-instance (which takes a System.Security.Principal.WindowsIdentity-instance, which you already have, as the ctor-parameter) and use it as the parameter?

    Otherwise: Did you know that CurrentPrincipal of a thread has a setter? Please see other so-question/answer