Freigeben über


Impersonating with Windows Security

I have a service that uses Windows authentication and want to impersonate the caller in one of the service operations. How should I configure the client and service?

There are a couple of things you need to do here to make this work.

On the client side, you need to give the client proxy your Windows credentials and permit it to perform the impersonation. The exact level of impersonation you need is something determined by your application. I'm using plain old Impersonate level impersonation in this example.

 client.ClientCredentials.Windows.ClientCredential.Domain = "MYDOMAIN";
client.ClientCredentials.Windows.ClientCredential.UserName = "User";
client.ClientCredentials.Windows.ClientCredential.Password = "Password";
client.ClientCredentials.Windows.AllowedImpersonationLevel =
   System.Security.Principal.TokenImpersonationLevel.Impersonation;

Your service process needs the SeImpersonatePrivilege.

Your operation needs to perform the impersonation. If you just want to impersonate for part of the operation, you can scope the impersonation block.

 using (ServiceSecurityContext.Current.WindowsIdentity.Impersonate())
{
...
}

You'd probably want to have some error handling for that block. If you want to impersonate for all of the operation, you can add an attribute to modify the operation behavior.

 [OperationBehavior(Impersonation = ImpersonationOption.Required)]

Finally, you can add a service behavior to instruct the service to impersonate the caller for all operations when allowed.

 host.Description.Behaviors.Find<ServiceAuthorizationBehavior>().ImpersonateCallerForAllOperations = true;

Next time: Use OneWay for Long-Running Operations

Comments