为什么端点上的Windows ClientCredential没有被使用?

时间:2012-11-02 15:03:41

标签: wcf

我有一个WCF通道工厂,其端点已针对WCF服务调用进行了修改。我想要的是服务调用是在通常直截了当的不同上下文中完成的。但它对我不起作用。我可以成功地将凭据添加到端点行为,检查它们并查看它们,但是不使用“NewUser”凭证进行呼叫。

internal static void UpdateChannelClientBehavior(ChannelFactory factory)
{
   factory.Endpoint.Behaviors.Remove<ClientCredentials>();
   //MyCustomCredentials is a custom class class variable that inherits System.ServiceModel.Description.ClientCredentials
   MyCustomCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
   MyCustomCredentials.Windows.ClientCredential = new NetworkCredential("NewUser", "password", "MyDomain");
   factory.Endpoint.Behaviors.Add(MyCustomCredentials);
   return;
}

因此,在此代码之后,端点确实具有新的Windows凭据,但是服务器端仍在默认上下文中调用,而不是且具有“NewUsers”凭据。我做错了什么才能使这项工作?

谢谢!

2 个答案:

答案 0 :(得分:0)

更改您的服务以使用“用户名”clientCredentialType而不是“Windows”。然后更改您的客户端以使用用户名和密码凭据。默认情况下,WCF将根据Windows帐户数据库检查凭据,除非您另行指定。

factory.Credentials.UserName.UserName = "NewUser";
factory.Credentials.UserName.Password = "password";

如果您使用“Windows”凭据类型,则无法更改它,它将始终位于正在运行的用户的上下文中。

答案 1 :(得分:0)

实际上这段代码确实有效:

internal static void UpdateChannelClientBehavior(ChannelFactory factory)
{
   factory.Endpoint.Behaviors.Remove<ClientCredentials>();
   //MyCustomCredentials is a custom class class variable that inherits System.ServiceModel.Description.ClientCredentials
   MyCustomCredentials.Windows.ClientCredential = new NetworkCredential("NewUser", "password", "MyDomain");
   factory.Endpoint.Behaviors.Add(MyCustomCredentials);
   return;
}

如果您直接实例化WCF客户端代理的实例,可以采用的另一种方法如下:

MyWcfService.MyWcfServiceServiceClient client = new MyWcfService.MyWcfServiceServiceClient();
client.ClientCredentials.Windows.ClientCredential = new NetworkCredential("NewUser", "password", "MyDomain");

我正在重复进行许多代码更改的尝试,并且搞砸了影响此代码的下游内容。您确实可以使用上面的代码更改呼叫的上下文,以模拟进行WCF呼叫的其他用户。如果需要临时提升对WCF服务的调用,这将非常方便