Share via


Configuring an Operation to Impersonate

Today's post is a supplement for those people annoyed that Using Impersonation with Transport Security doesn't actually explain how to use impersonation. Most of the questions that I've seen for this topic come from people that already know how Windows impersonation is supposed to work. This means that they've gotten started by sticking a basic block somewhat like this one from one of our samples into their operation.

 WindowsIdentity callerIdentity = ServiceSecurityContext.Current.WindowsIdentity;
if (callerIdentity == null)
{
   // fail...
}
using (callerIdentity.Impersonate())
{
   // do something here...
}

The alternative to doing all this work is to set the ImpersonateCallerForAllOperations property on the ServiceAuthorizationBehavior of your service. This has the obvious effect of using impersonation for all of your operations. The question then is how to get this block of code working with WCF. Impersonation involves setup work on both the client and server. On the server, the implementation needs to be decorated with an attribute stating that impersonation is being used in this operation.

 [OperationBehavior(Impersonation = ImpersonationOption.Required)]

Depending on what you actually want to do in your operation, this may be enough to get your application working. However, if you need a specific impersonation level, for example to access remote resources, then the client needs to give explicit permission. The maximum impersonation level is set on the Windows credentials of the client proxy.

 client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Delegation;

Here's where the original article is useful by explaining what the various impersonation levels do and when you can use them.

Note that the ASP.NET impersonation feature is supported when you're using ASP.NET compatibility mode. However, you have to choose between configuring impersonation through ASP.NET or WCF. If you've configured the WCF impersonation settings, then those are the settings that we use. Otherwise, we look at the ASP.NET impersonation settings. ASP.NET impersonation is not available when you're using transport security but sending the credentials using message security.

Next time: Secure MEX Endpoints