tags:

views:

44

answers:

1

I have a Windows Form app (4.0) that calls a Web Service (WCF) but needs to impersonate a different user than who is currently logged inot the machine. How can that be done? Right now the Web Service is failing to return records because the user does not have the rights. I need to use a different user for the Web Service call.

+1  A: 

From my app where I do this:

NetworkCredential credentials = new NetworkCredential(user, pw, userDomain);

//  This is the client generated by the WCF Service Reference
AppClient appClient = new AppClient();

appClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
appClient.ClientCredentials.Windows.ClientCredential = credentials;

appClient.MyWcfServiceCall();

Now calls to the WCF service will be done under the credentials supplied. Your WCF Service methods must be decorated to allow impersonation as such:

[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]

or

[OperationBehavior(Impersonation = ImpersonationOption.Required)]

depending on your needs.

From within the WCF Service, you have the following info about the logged on user:

OperationContext.Current.ServiceSecurityContext
Thread.CurrentPrincipal.IsInRole(roleName)
Thread.CurrentPrincipal.Identity

You can also look into LogonUser() for other methods of impersonation: http://msdn.microsoft.com/en-us/library/ff647404.aspx#paght000023_impersonatingusinglogonuser

HTH! James

James B