WCF TCP Windows身份验证问题

本文关键字:问题 身份验证 Windows TCP WCF | 更新日期: 2023-09-27 18:10:32

我有一个情况,我有两台机器。

  • 机器B

机器B上的客户端成功连接到机器a上的主机。

机器B上的客户端成功连接到机器B上的主机

机器A上的客户端成功连接到机器b上的主机

机器A上的客户端不能连接到机器A上的主机。

安全协商异常:服务器拒绝了客户端凭据。

我正在使用Windows身份验证。

客户:

        var netTcpBinding = new NetTcpBinding()
        {
            Security = new NetTcpSecurity()
            {
                Mode = SecurityMode.Transport,
                Transport = new TcpTransportSecurity()
                {
                    ClientCredentialType = TcpClientCredentialType.Windows,
                }
            },
            TransferMode = TransferMode.Streamed,
            MaxReceivedMessageSize = long.MaxValue,
            MaxBufferSize = int.MaxValue,
            MaxBufferPoolSize = long.MaxValue,
            ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
            {
                MaxDepth = int.MaxValue,
                MaxArrayLength = int.MaxValue,
                MaxStringContentLength = int.MaxValue
            },
            SendTimeout = TimeSpan.MaxValue,
            ReceiveTimeout = TimeSpan.MaxValue
        };
        string endpointAddress;
        if (port == 0)
            endpointAddress = string.Format("net.tcp://{0}/Configuration", host);
        else
            endpointAddress = string.Format("net.tcp://{0}:{1}/Configuration", host, port);
        Console.WriteLine("Endpoint: {0}", endpointAddress);
        var factory = new ChannelFactory<IMyChannel>(netTcpBinding);
        factory.Endpoint.Address = new EndpointAddress(new Uri(endpointAddress), new DnsEndpointIdentity("MyDns"));
        //Do not verify
        factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
        factory.Credentials.Windows.ClientCredential.Domain = domain;
        factory.Credentials.Windows.ClientCredential.UserName = username;
        factory.Credentials.Windows.ClientCredential.Password = password;
        //Console.WriteLine("Opening Channel Factory ... ");
        factory.Open();

主持人:

    #region INIT
    //Set configuration file just once
    if (ChannelServices.RegisteredChannels.Length == 0)
    {
        RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, false);
    }
    _serviceHost = null;
    _serviceHost = new ServiceHost(typeof(MyChannel));
    _serviceHost.AddDefaultEndpoints();
    // build list with local IP addresses to bind to
    var localIpAddresses = new List<IPAddress>(Dns.GetHostAddresses(Dns.GetHostName()));
    if (IPAddress.Loopback != null)
        localIpAddresses.Add(IPAddress.Loopback);
    localIpAddresses.RemoveAll(i => i.AddressFamily != AddressFamily.InterNetwork);
    // enable metadata exchange bahaviour
    // add metadatabehaviour in case HTTP is not enabled
    var metadataBehaviour = _serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
    if (metadataBehaviour == null)
    {
        metadataBehaviour = new ServiceMetadataBehavior();
        _serviceHost.Description.Behaviors.Add(metadataBehaviour);
    }
    var credentialsBehaviour = _serviceHost.Description.Behaviors.Find<ServiceCredentials>();
    if (credentialsBehaviour == null)
    {
        credentialsBehaviour = new ServiceCredentials();
        _serviceHost.Description.Behaviors.Add(credentialsBehaviour);
    }
    var serviceDebug = _serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
    if (serviceDebug == null)
    {
        serviceDebug = new ServiceDebugBehavior();
        _serviceHost.Description.Behaviors.Add(serviceDebug);
    }
    serviceDebug.IncludeExceptionDetailInFaults = true;
    var tcpPort = "9096";
    _log.Info("tcpPort - {0}", tcpPort);
    var netTcpBinding = new NetTcpBinding()
    {
        Security = new NetTcpSecurity()
        {
            Mode = SecurityMode.Transport,
            Transport = new TcpTransportSecurity()
            {
                ClientCredentialType = TcpClientCredentialType.Windows,
            }
        },
        TransferMode = TransferMode.Streamed,
        MaxReceivedMessageSize = long.MaxValue,
        MaxBufferSize = int.MaxValue,
        MaxBufferPoolSize = long.MaxValue,
        ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
        {
            MaxDepth = int.MaxValue,
            MaxArrayLength = int.MaxValue,
            MaxStringContentLength = int.MaxValue
        },
        SendTimeout = TimeSpan.MaxValue,
        ReceiveTimeout = TimeSpan.MaxValue
    };
    var endpoint = _serviceHost.AddServiceEndpoint(
        typeof(IMyChannel),
        netTcpBinding,
        new Uri(string.Format("net.tcp://0:{0}/Configuration", tcpPort)));
    ServiceSecurityAuditBehavior newAudit = new ServiceSecurityAuditBehavior();
    newAudit.AuditLogLocation = AuditLogLocation.Application;
    newAudit.MessageAuthenticationAuditLevel = AuditLevel.SuccessOrFailure;
    newAudit.ServiceAuthorizationAuditLevel = AuditLevel.SuccessOrFailure;
    newAudit.SuppressAuditFailure = false;
    _serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
        MetadataExchangeBindings.CreateMexTcpBinding(),
        string.Format("net.tcp://localhost:{0}/Configuration/mex", tcpPort));
    _serviceHost.Description.Behaviors.Remove<ServiceSecurityAuditBehavior>();
    _serviceHost.Description.Behaviors.Add(newAudit);
    _serviceHost.Opening += (sender, eventArgs) => _log.Info("Opening Connection ...");
    _serviceHost.Opened += (sender, eventArgs) => _log.Info("Opened Connection ...");
    _serviceHost.Closing += (sender, eventArgs) => _log.Info("Closing connection ...");
    _serviceHost.Closed += (sender, eventArgs) => _log.Info("Closed connection ...");
    _serviceHost.Faulted += (sender, eventArgs) => _log.Error("Fault detected on WCF host");
    _serviceHost.Open();
    #endregion

这是我的完整堆栈跟踪:

System.ServiceModel.Security。SecurityNegotiationException:服务器已经拒绝了Ed的客户凭证。--->System.Security.Authentication.InvalidCredential异常:服务器已拒绝客户端凭据。——>系统。组件模型。Win32Exception: The logon attempt失败——End of inner异常堆栈跟踪——atSystem.Net.Security.NegoState。ProcessReceivedBlob (Byte[]消息,懒散的结果)System.Net.Security.NegoState。StartSendBlob (Byte[]消息,lazyasyncresult lazyResult) atSystem.Net.Security.NegoState.CheckCompletionBeforeNextSend (Byte []消息,LazyAsyncResult lazyResult)System.Net.Security.NegoState。ProcessReceivedBlob (Byte[]消息,懒散的结果)System.Net.Security.NegoState。StartSendBlob (Byte[]消息,lazyasyncresult lazyResult) atSystem.Net.Security.NegoState.ProcessAuthentication (LazyAsyncResult懒惰的;懒惰的System.Net.Security.NegotiateStream.AuthenticateAsClient (NetworkCredentialcredential, String targetName, ProtectionLevelrequiredProtectionLevel, tokeninpersonationlevelallowedImpersonationLevel)System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator。OnInitiateUpgrade(流流,SecurityMessagePr operty&remotessecurity)——内部安全结束异常堆栈跟踪——

服务器堆栈跟踪:atSystem.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator。OnInitiateUpgrade(流流,SecurityMessagePr operty&remoteSecurity)System.ServiceModel.Channels.StreamSecurityUpgradeInitiatorBase.InitiateUp等级(溪流)在System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade (StreamUpgradeInitiator upgradeInitiator;连接,ClientFramingDecode解码器,IDefaultCommunicationTimeoutsdefaultTimeouts TimeoutHelper&超时Helper)System.ServiceModel.Channels.StreamedFramingRequestChannel.SendPreamble(集成电路连接连接,TimeoutHelper&timeoutHelper,ClientFramingDecoder, SecurityMessageProperty&remoteSecurity)System.ServiceModel.Channels.StreamedFramingRequestChannel.StreamedConnectionPoolHelper。AcceptPooledConnection (IConnection连接,TimeoutHelper&超时;超时System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(时间Span超时)System.ServiceModel.Channels.StreamedFramingRequestChannel.StreamedFraming请求。SendRequest(Message消息,TimeSpan超时)System.ServiceModel.Channels.RequestChannel。请求(消息消息,TimeS(平移超时)atSystem.ServiceModel.Channels.ServiceChannel。调用(字符串操作,Boolean on way, ProxyOperationRuntime操作,Object[] in,Object[] out, TimeSpan time out) atSystem.ServiceModel.Channels.ServiceChannelProxy.InvokeService (IMethodCall消息方法调用,ProxyOperationRuntime操作)System.ServiceModel.Channels.ServiceChannelProxy.Invoke (IMessage消息)

异常重新抛出在[0]:atSystem.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage (IMessagereqmsg, IMessage, retMsg) atSystem.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke (MessageData&msgDa数据,Int32类型)在MyProject.TestConnection()在MyProject. program . manualinput () in d:'Source'MyProject'Program.cs:line84

这没有任何意义。

任何帮助将不胜感激!

谢谢!

K

WCF TCP Windows身份验证问题

解决!

这个问题是DnsEndpointIdentity不需要用于windows身份验证:)