双工回调始终是匿名的

6 c# wcf duplex servicehost wcf-callbacks

我写了一个WCF双工服务和客户端.一切正常,直到我尝试在客户端实现中调用.Demand().服务似乎是匿名调用回调方法.我想我错过了如何正确配置服务.

用于创建ServiceHost的代码;

ServiceHost duplex = new ServiceHost(new ServerWCallbackImpl());           
NetTcpBinding secureBinding = new NetTcpBinding(SecurityMode.Message);
secureBinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
duplex.AddServiceEndpoint(typeof(IServerWithCallback),
    secureBinding,
    "net.tcp://localhost:9080/DataService");
Console.WriteLine(Thread.CurrentPrincipal.Identity.Name); //<-- this correctly shows the current principal
duplex.Open();
if (duplex.State == CommunicationState.Opened) 
    ((ServerWCallbackImpl)duplex.SingletonInstance).Send("Hello World!");
Run Code Online (Sandbox Code Playgroud)

用于创建客户端的代码;

CallbackImpl callbackInstance = new CallbackImpl();
NetTcpBinding secureBinding = new NetTcpBinding(SecurityMode.Message);
secureBinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
DuplexChannelFactory<IServerWithCallback> cf = new DuplexChannelFactory<IServerWithCallback>(
    callbackInstance,
    secureBinding,
    new EndpointAddress(requestingEndpointAddress));           
cf.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
cf.Credentials.Windows.ClientCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
IServerWithCallback srv = cf.CreateChannel(new InstanceContext(callbackInstance));
srv.InitiateConversation();
Run Code Online (Sandbox Code Playgroud)

客户实施:

public void MethodOnClient(string message)
{
    Console.WriteLine(Thread.CurrentPrincipal.Identity.Name);  // <-- anonymous
    PrincipalPermission p = new PrincipalPermission(@"DOMAIN\User", null);
    p.Demand();  // <-- fails
}
Run Code Online (Sandbox Code Playgroud)

如何配置以便ServiceHost使用Windows凭据正确调用Callback?

小智 0

是否将 TokenImpersonationLevel 设置为 delegate 而不是 Impersonation?像这样:

cf.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
Run Code Online (Sandbox Code Playgroud)

请参阅这篇 MSDN 文章