How to Impersonate Programmatically In WCF

Programmatic impersonation allows you to impersonate on specific lines of code rather than the entire operation. This finer-grained approach to impersonation can reduce security risk, however be aware that it is easier to make a mistake during implementation
that could leave your code impersonating at higher privilege in the event of an error. Use the
using statement to revert impersonation automatically.

To impersonate the original caller programmatically, you need to have access to Windows Identity of the original caller, calling into your WCF service. For this you need to configure your WCF service to require Windows Authentication. Programmatic impersonation
allows you to impersonate on specific lines of code rather than the entire operation.

Use the Impersonate method of the ServiceSecurityContext.Current.WindowsIdentity class, as shown here.

public string GetData(int value)
{
using (*ServiceSecurityContext*.Current.WindowsIdentity.*Impersonate*())
{
// Execute under security context of the original caller
}
}

Important: Revert the impersonation when you are done, in the above example the
using statement does it for you.