public override bool TryImportWsspHttpsTokenAssertion(MetadataImporter importer, ICollection<XmlElement> assertions, HttpsTransportBindingElement httpsBinding)
 {
     XmlElement element;
     if (assertions == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertions");
     }
     if (this.TryImportWsspAssertion(assertions, "HttpsToken", out element))
     {
         bool flag = true;
         string attribute = element.GetAttribute("RequireClientCertificate");
         try
         {
             httpsBinding.RequireClientCertificate = XmlUtil.IsTrue(attribute);
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             if (exception is NullReferenceException)
             {
                 throw;
             }
             importer.Errors.Add(new MetadataConversionError(System.ServiceModel.SR.GetString("UnsupportedBooleanAttribute", new object[] { "RequireClientCertificate", exception.Message }), false));
             flag = false;
         }
         return flag;
     }
     return false;
 }
Пример #2
0
        public static PhasorDataServiceClient GetPhasorDataServiceProxyClient()
        {
            string baseServiceUrl = Application.Current.Resources["BaseServiceUrl"].ToString();
            EndpointAddress address = new EndpointAddress(baseServiceUrl + "Service/PhasorDataService.svc");
            CustomBinding binding;

            if (HtmlPage.Document.DocumentUri.Scheme.ToLower().StartsWith("https"))
            {
                HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement();
                httpsTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;		// 65536 * 50;
                binding = new CustomBinding(
                                    new BinaryMessageEncodingBindingElement(),
                                    httpsTransportBindingElement
                                    );
            }
            else
            {
                HttpTransportBindingElement httpTransportBindingElement = new HttpTransportBindingElement();
                httpTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;	// 65536 * 50;
                binding = new CustomBinding(
                                    new BinaryMessageEncodingBindingElement(),
                                    httpTransportBindingElement
                                    );
            }

            binding.CloseTimeout = new TimeSpan(0, 20, 0);
            binding.OpenTimeout = new TimeSpan(0, 20, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 20, 0);
            binding.SendTimeout = new TimeSpan(0, 20, 0);

            return new PhasorDataServiceClient(binding, address);
        }
Пример #3
0
        public static OmnitureWebServicePortTypeClient GetClient( string username, string secret, string endpoint )
        {
            var httpsTransportBindingElement = new HttpsTransportBindingElement
                                                   {
                                                       UseDefaultWebProxy = false,
                                                       MaxReceivedMessageSize = 2147483647
                                                   };

            var transportSecurityBindingElement = new TransportSecurityBindingElement();
            transportSecurityBindingElement.EndpointSupportingTokenParameters.SignedEncrypted.Add( new SecurityTokenParameters() );
            transportSecurityBindingElement.IncludeTimestamp = false;

            var customTextMessageBindingElement = new CustomTextMessageBindingElement { MessageVersion = MessageVersion.Soap11 };

            var bindingElements = new List<BindingElement>
                                  {
                                      transportSecurityBindingElement,
                                      customTextMessageBindingElement,
                                      httpsTransportBindingElement
                                  };

            Binding customBinding = new CustomBinding( bindingElements.ToArray() );
            var endpointAddress = new EndpointAddress( endpoint );
            var clientCredential = new ClientCredentials( new Info( username, secret ) );

            var omnitureWebServicePortTypeClient = new OmnitureWebServicePortTypeClient( customBinding, endpointAddress );
            omnitureWebServicePortTypeClient.Endpoint.Behaviors.Remove( typeof( System.ServiceModel.Description.ClientCredentials ) );
            omnitureWebServicePortTypeClient.Endpoint.Behaviors.Add( clientCredential );

            return omnitureWebServicePortTypeClient;
        }
        public override XmlElement CreateWsspHttpsTokenAssertion(MetadataExporter exporter, HttpsTransportBindingElement httpsBinding)
        {
            Fx.Assert(httpsBinding != null, "httpsBinding must not be null.");
            Fx.Assert(httpsBinding.AuthenticationScheme.IsSingleton(), "authenticationScheme must be a singleton value for security-mode TransportWithMessageCredential.");

            XmlElement result = CreateWsspAssertion(WSSecurityPolicy.HttpsTokenName);
            if (httpsBinding.RequireClientCertificate ||
                httpsBinding.AuthenticationScheme == AuthenticationSchemes.Basic ||
                httpsBinding.AuthenticationScheme == AuthenticationSchemes.Digest)
            {
                XmlElement policy = CreateWspPolicyWrapper(exporter);
                if (httpsBinding.RequireClientCertificate)
                {
                    policy.AppendChild(CreateWsspAssertion(WSSecurityPolicy.RequireClientCertificateName));
                }
                if (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Basic)
                {
                    policy.AppendChild(CreateWsspAssertion(WSSecurityPolicy.HttpBasicAuthenticationName));
                }
                else if (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Digest)
                {
                    policy.AppendChild(CreateWsspAssertion(WSSecurityPolicy.HttpDigestAuthenticationName));
                }
                result.AppendChild(policy);
            }
            return result;
        }
        internal static void ConfigureTransportProtectionAndAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpsTransportBindingElement httpsTransportBindingElement)
        {
            Debug.Assert(httpTransportSecurity != null, "httpTransportSecurity cannot be null");
            Debug.Assert(httpsTransportBindingElement != null, "httpsTransportBindingElement cannot be null");

            httpTransportSecurity.ConfigureAuthentication(httpsTransportBindingElement);
            httpsTransportBindingElement.RequireClientCertificate = httpTransportSecurity.ClientCredentialType == HttpClientCredentialType.Certificate;
        }
 internal static void ConfigureTransportProtectionAndAuthentication(HttpsTransportBindingElement https, HttpTransportSecurity transportSecurity)
 {
     ConfigureAuthentication(https, transportSecurity);
     if (https.RequireClientCertificate)
     {
         transportSecurity.ClientCredentialType = HttpClientCredentialType.Certificate;
     }
 }
 private void AddWindowsHttpsTransportBindingElement(BindingElementCollection bindingElements)
 {
     HttpsTransportBindingElement item = new HttpsTransportBindingElement {
         RequireClientCertificate = false,
         UseDefaultWebProxy = false,
         AuthenticationScheme = AuthenticationSchemes.Negotiate
     };
     bindingElements.Add(item);
 }
Пример #8
0
        internal HttpBindingBase()
        {
            _httpTransport = new HttpTransportBindingElement();
            _httpsTransport = new HttpsTransportBindingElement();

            _textEncoding = new TextMessageEncodingBindingElement();
            _textEncoding.MessageVersion = MessageVersion.Soap11;
            _httpsTransport.WebSocketSettings = _httpTransport.WebSocketSettings;
        }
Пример #9
0
		private static HttpTransportBindingElement CreateTransportBindingElement(bool useTls){
			if(useTls){
				var transport = new HttpsTransportBindingElement();
				transport.RequireClientCertificate = false;
				return transport;
			}else{
				return new HttpTransportBindingElement();
			}
		}
        private void Initialize()
        {
            _securityBindingElement = CreateSecurityBindingElement();

            _reliableSessionBindingElement = CreateReliableSessionBindingElement();

            _mtomEncodingBindingElement = CreateMtomEncodingBindingElement();

            _httpsTransportBindingElement = CreateHttpsTransportBindingElement() as HttpsTransportBindingElement;
        }
 internal void EnableTransportSecurity(HttpsTransportBindingElement https)
 {
     if (this.mode == BasicHttpSecurityMode.TransportWithMessageCredential)
     {
         this.transportSecurity.ConfigureTransportProtectionOnly(https);
     }
     else
     {
         this.transportSecurity.ConfigureTransportProtectionAndAuthentication(https);
     }
 }
Пример #12
0
        internal HttpBindingBase()
        {
            this.httpTransport = new HttpTransportBindingElement();
            this.httpsTransport = new HttpsTransportBindingElement();

            this.textEncoding = new TextMessageEncodingBindingElement();
            this.textEncoding.MessageVersion = MessageVersion.Soap11;
            this.mtomEncoding = new MtomMessageEncodingBindingElement();
            this.mtomEncoding.MessageVersion = MessageVersion.Soap11;

            this.httpsTransport.WebSocketSettings = this.httpTransport.WebSocketSettings;
        }
        private void Initialize()
        {
            _securityBindingElement = CreateSecurityBindingElement();

            _reliableSessionBindingElement = CreateReliableSessionBindingElement();

            _textEncodingBindingElement = CreateTextEncodingBindingElement();

            _httpsTransportBindingElement = CreateHttpsTransportBindingElement();

            //_httpTransportBindingElement = CreateHttpTransportBindingElement();
        }
 private void Initialize()
 {
     this.httpTransport = new HttpTransportBindingElement();
     this.httpsTransport = new HttpsTransportBindingElement();
     this.messageEncoding = WSMessageEncoding.Text;
     this.txFlow = GetDefaultTransactionFlowBindingElement();
     this.session = new System.ServiceModel.Channels.ReliableSessionBindingElement(true);
     this.textEncoding = new TextMessageEncodingBindingElement();
     this.textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
     this.mtomEncoding = new MtomMessageEncodingBindingElement();
     this.mtomEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
     this.reliableSession = new OptionalReliableSession(this.session);
 }
        private HttpsTransportBindingElement CreateHttpsTransportBindingElement()
        {
            HttpsTransportBindingElement transportBindingElement = new HttpsTransportBindingElement();

            // When set to true, the IIS Site application must have the SSL require certificate set
            transportBindingElement.RequireClientCertificate = false;

            transportBindingElement.MaxBufferSize = 524288;
            transportBindingElement.MaxReceivedMessageSize = 200000000;
            transportBindingElement.MaxBufferSize = 200000000;

            return transportBindingElement;
        }
        private void Initialize()
        {
            _securityBindingElement = CreateSecurityBindingElement();
            //_securityBindingElement = CreateTransportSecurityBindingElement();

            _reliableSessionBindingElement = CreateReliableSessionBindingElement();

            //binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10, Encoding.UTF8));

            _mtomEncodingBindingElement = CreateMtomEncodingBindingElement();

            _httpsTransportBindingElement = CreateHttpsTransportBindingElement() as HttpsTransportBindingElement;
        }
        public override bool TryImportWsspHttpsTokenAssertion(MetadataImporter importer, ICollection<XmlElement> assertions, HttpsTransportBindingElement httpsBinding)
        {
            if (assertions == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertions");
            }

            bool result = true;
            XmlElement assertion;

            if (TryImportWsspAssertion(assertions, HttpsTokenName, out assertion))
            {
                XmlElement policyElement = null;
                foreach (XmlNode node in assertion.ChildNodes)
                {
                    if (node is XmlElement && node.LocalName == WSSecurityPolicy.PolicyName && (node.NamespaceURI == WSSecurityPolicy.WspNamespace || node.NamespaceURI == WSSecurityPolicy.Wsp15Namespace))
                    {
                        policyElement = (XmlElement)node;
                        break;
                    }
                }

                if (policyElement != null)
                {
                    foreach (XmlNode node in policyElement.ChildNodes)
                    {
                        if (node is XmlElement && node.NamespaceURI == this.WsspNamespaceUri)
                        {
                            if (node.LocalName == WSSecurityPolicy.RequireClientCertificateName)
                            {
                                httpsBinding.RequireClientCertificate = true;
                            }
                            else if (node.LocalName == WSSecurityPolicy.HttpBasicAuthenticationName)
                            {
                                httpsBinding.AuthenticationScheme = AuthenticationSchemes.Basic;
                            }
                            else if (node.LocalName == WSSecurityPolicy.HttpDigestAuthenticationName)
                            {
                                httpsBinding.AuthenticationScheme = AuthenticationSchemes.Digest;
                            }
                        }
                    }
                }
            }
            else
            {
                result = false;
            }

            return result;
        }
Пример #18
0
        public NetHttpBinding(NetHttpSecurityMode securityMode)
        {
            if (securityMode != NetHttpSecurityMode.Transport &&
                securityMode != NetHttpSecurityMode.TransportCredentialOnly &&
                securityMode != NetHttpSecurityMode.None)
            {
                throw new ArgumentOutOfRangeException("securityMode");
            }

            this.securityMode = securityMode;   
            this.httpTransport = new HttpTransportBindingElement();
            this.httpsTransport = new HttpsTransportBindingElement();
            this.binaryEncoding = new BinaryMessageEncodingBindingElement();
        }
		public void GetProperty ()
		{
			var b = new HttpsTransportBindingElement ();
			var s = b.GetProperty<ISecurityCapabilities> (new BindingContext (new CustomBinding (), new BindingParameterCollection ()));
			Assert.IsNotNull (s, "#1");
			Assert.AreEqual (ProtectionLevel.EncryptAndSign, s.SupportedRequestProtectionLevel, "#2");
			Assert.AreEqual (ProtectionLevel.EncryptAndSign, s.SupportedResponseProtectionLevel, "#3");
			Assert.IsFalse (s.SupportsClientAuthentication, "#4");
			Assert.IsFalse (s.SupportsClientWindowsIdentity, "#5");
			Assert.IsTrue (s.SupportsServerAuthentication, "#6");

			b.RequireClientCertificate = true;
			s = b.GetProperty<ISecurityCapabilities> (new BindingContext (new CustomBinding (), new BindingParameterCollection ()));
			Assert.IsTrue (s.SupportsClientAuthentication, "#7");
			Assert.IsTrue (s.SupportsClientWindowsIdentity, "#8");
		}
Пример #20
0
        public GeocachingLiveV6(bool testSite)
        {

            BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement()
            {
                ReaderQuotas = new XmlDictionaryReaderQuotas()
                {
                    MaxStringContentLength = int.MaxValue,
                    MaxBytesPerRead = int.MaxValue,
                    MaxDepth = int.MaxValue,
                    MaxArrayLength = int.MaxValue
                }
            };

            HttpTransportBindingElement httpTransport = new HttpsTransportBindingElement()
            {
                MaxBufferSize = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                AllowCookies = false,
                //UseDefaultWebProxy = true,
            };

            // add the binding elements into a Custom Binding
            CustomBinding binding = new CustomBinding(binaryMessageEncoding, httpTransport);

            EndpointAddress endPoint;
            if (testSite)
            {
                endPoint = new EndpointAddress("https://staging.api.groundspeak.com/Live/V6Beta/geocaching.svc/Silverlightsoap");
                _token = Core.Settings.Default.LiveAPITokenStaging;
            }
            else
            {
                endPoint = new EndpointAddress("https://api.groundspeak.com/LiveV6/Geocaching.svc/Silverlightsoap");
                _token = Core.Settings.Default.LiveAPIToken;
            }

            try
            {
                _client = new LiveV6.LiveClient(binding, endPoint);
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }

        }
Пример #21
0
        private void CreateServiceHost(Uri uri, string subjectName = null)
        {
            if (host != null) return;

            CustomBinding binding = new CustomBinding();
            binding.Elements.Add(new ByteStreamMessageEncodingBindingElement());

            HttpTransportBindingElement transport;
            ServiceCredentials behavior = null;
            string scheme;
            if (uri.Scheme.Equals("ws"))
            {
                transport = new HttpTransportBindingElement();
                scheme = Uri.UriSchemeHttp;
            }
            else
            {
                transport = new HttpsTransportBindingElement();
                scheme = Uri.UriSchemeHttps;
                behavior = new ServiceCredentials();
                behavior.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine,
                    StoreName.My, X509FindType.FindBySubjectName, subjectName);
            }

            transport.WebSocketSettings = new WebSocketTransportSettings()
            {
                TransportUsage = WebSocketTransportUsage.Always,
                CreateNotificationOnConnection = false
            };
            binding.Elements.Add(transport);

            host = new ServiceHost(typeof(WebSocketServerTool.Service));

            UriBuilder newUri = new UriBuilder(uri)
            {
                Scheme = scheme
            };

            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService),
                binding, newUri.ToString());

            if (behavior != null)
                host.Description.Behaviors.Add(behavior);

            host.Open();
        }
Пример #22
0
        public GeocachingLiveV6(Framework.Interfaces.ICore core, bool testSite)
        {
            _core = core;

            BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement()
            {
                ReaderQuotas = new XmlDictionaryReaderQuotas()
                {
                    MaxStringContentLength = int.MaxValue,
                    MaxBytesPerRead = int.MaxValue,
                    MaxDepth = int.MaxValue,
                    MaxArrayLength = int.MaxValue
                }
            };

            HttpTransportBindingElement httpTransport = new HttpsTransportBindingElement() 
            { 
                MaxBufferSize = int.MaxValue, 
                MaxReceivedMessageSize = int.MaxValue,
                AllowCookies = false, 
            };

            // add the binding elements into a Custom Binding
            CustomBinding binding = new CustomBinding(binaryMessageEncoding, httpTransport);            

            EndpointAddress endPoint;
            if (testSite)
            {
                endPoint = new EndpointAddress("https://staging.api.groundspeak.com/Live/V6Beta/geocaching.svc/Silverlightsoap");
                _token = core.GeocachingComAccount.APITokenStaging;
            }
            else
            {
                endPoint = new EndpointAddress("https://api.groundspeak.com/LiveV6/Geocaching.svc/Silverlightsoap");
                _token = core.GeocachingComAccount.APIToken;
            }

            try
            {
                _client = new LiveV6.LiveClient(binding, endPoint);
            }
            catch
            {
            }

        }
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaHttpsSoapBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                TransportSecurityBindingElement bootstrap = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
                bootstrap.IncludeTimestamp = true;
                bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                bootstrap.SecurityHeaderLayout = SecurityHeaderLayout.Strict;

                m_security = SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap);
                m_security.IncludeTimestamp = true;
                m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                m_security.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
            }

            m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8);
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new HttpsTransportBindingElement();

            m_transport.AllowCookies           = false;
            m_transport.AuthenticationScheme   = System.Net.AuthenticationSchemes.Anonymous;
            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferSize          = configuration.MaxMessageSize;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
            m_transport.TransferMode           = TransferMode.Buffered;
        }
 private CustomBinding CreateCustomBinding()
 {
     var binding = new CustomBinding();
     var securityBinding =
         SecurityBindingElement.CreateCertificateOverTransportBindingElement(
             MessageSecurityVersion
                 .WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
     securityBinding.IncludeTimestamp = true;
     securityBinding.AllowInsecureTransport = true;
     securityBinding.EnableUnsecuredResponse = true;
     binding.Elements.Add(securityBinding);
     binding.Elements.Add(new CustomTextMessageBindingElement(_difiGatewaySettings));
     var httpsTransportBinding = new HttpsTransportBindingElement();
     httpsTransportBinding.MaxReceivedMessageSize = Int32.MaxValue;
     binding.Elements.Add(httpsTransportBinding);
     return binding;
 }
 private static TransportBindingElement CreateTransportBindingElements(string transportUri, PolicyConversionContext policyContext)
 {
     TransportBindingElement element = null;
     string str = transportUri;
     if (str != null)
     {
         if (!(str == "http://schemas.xmlsoap.org/soap/http"))
         {
             if (str == "http://schemas.microsoft.com/soap/tcp")
             {
                 return new TcpTransportBindingElement();
             }
             if (str == "http://schemas.microsoft.com/soap/named-pipe")
             {
                 return new NamedPipeTransportBindingElement();
             }
             if (str == "http://schemas.microsoft.com/soap/msmq")
             {
                 return new MsmqTransportBindingElement();
             }
             if (str != "http://schemas.microsoft.com/soap/peer")
             {
                 return element;
             }
             return new PeerTransportBindingElement();
         }
         if (policyContext != null)
         {
             WSSecurityPolicy securityPolicy = null;
             ICollection<XmlElement> bindingAssertions = policyContext.GetBindingAssertions();
             if (WSSecurityPolicy.TryGetSecurityPolicyDriver(bindingAssertions, out securityPolicy) && securityPolicy.ContainsWsspHttpsTokenAssertion(bindingAssertions))
             {
                 HttpsTransportBindingElement element2 = new HttpsTransportBindingElement {
                     MessageSecurityVersion = securityPolicy.GetSupportedMessageSecurityVersion(SecurityVersion.WSSecurity11)
                 };
                 element = element2;
             }
         }
         if (element == null)
         {
             element = new HttpTransportBindingElement();
         }
     }
     return element;
 }
        public SspiNegotiatedOverTransportBinding()
        {
            //add  security
            var securityElement =
                SecurityBindingElement.CreateSspiNegotiationOverTransportBindingElement();

            // Add login

            Elements.Add(securityElement);

            // Message Encoding
            var textEncoding = new TextMessageEncodingBindingElement();
            textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10;
            Elements.Add(textEncoding);

            // Transport
            var transport = new HttpsTransportBindingElement();
            Elements.Add(transport);
        }
Пример #27
0
        public void HttpTransportSecurity_ConfigureTransportAuthentication_Https()
        {
            ExtendedProtectionPolicy policy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
            HttpTransportSecurity security = new HttpTransportSecurity()
            {
                ClientCredentialType = HttpClientCredentialType.Basic,
                ProxyCredentialType = HttpProxyCredentialType.Basic,
                Realm = "MyRealm",
                ExtendedProtectionPolicy = policy
            };
            HttpsTransportBindingElement binding = new HttpsTransportBindingElement();

            security.ConfigureTransportAuthentication(binding);

            Assert.AreEqual(AuthenticationSchemes.Basic, binding.AuthenticationScheme, "AuthenticationScheme failed to init");
            Assert.AreEqual(AuthenticationSchemes.Basic, binding.ProxyAuthenticationScheme, "ProxyAuthenticationScheme failed to init");
            Assert.AreEqual("MyRealm", binding.Realm, "Realm failed to init");
            Assert.AreEqual(policy, binding.ExtendedProtectionPolicy, "ExtendedProtectionPolicy failed to init");
        }
 public override XmlElement CreateWsspHttpsTokenAssertion(MetadataExporter exporter, HttpsTransportBindingElement httpsBinding)
 {
     XmlElement element = this.CreateWsspAssertion("HttpsToken");
     if ((httpsBinding.RequireClientCertificate || (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Basic)) || (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Digest))
     {
         XmlElement newChild = this.CreateWspPolicyWrapper(exporter, new XmlElement[0]);
         if (httpsBinding.RequireClientCertificate)
         {
             newChild.AppendChild(this.CreateWsspAssertion("RequireClientCertificate"));
         }
         if (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Basic)
         {
             newChild.AppendChild(this.CreateWsspAssertion("HttpBasicAuthentication"));
         }
         else if (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Digest)
         {
             newChild.AppendChild(this.CreateWsspAssertion("HttpDigestAuthentication"));
         }
         element.AppendChild(newChild);
     }
     return element;
 }
Пример #29
0
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaHttpsSoapBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {
            m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8);
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new HttpsTransportBindingElement();

            m_transport.AllowCookies           = false;
            m_transport.AuthenticationScheme   = System.Net.AuthenticationSchemes.Anonymous;
            m_transport.BypassProxyOnLocal     = true;
            m_transport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            m_transport.KeepAliveEnabled       = true;
            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferPoolSize      = Int32.MaxValue;
            m_transport.MaxBufferSize          = configuration.MaxMessageSize;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
            m_transport.TransferMode           = TransferMode.Buffered;
            m_transport.UseDefaultWebProxy     = false;
        }
        /// <summary>
        /// Creates an endpoint based on the specified address.
        /// </summary>
        /// <param name="contract">The endpoint's contract.</param>
        /// <param name="address">The endpoint's base address.</param>
        /// <returns>An endpoint.</returns>
        private ServiceEndpoint CreateEndpointForAddress(ContractDescription contract, Uri address)
        {
            PoxBinaryMessageEncodingBindingElement encoding = new PoxBinaryMessageEncodingBindingElement();
            ServiceUtility.SetReaderQuotas(encoding.ReaderQuotas);

            HttpTransportBindingElement transport;
            if (address.Scheme.Equals(Uri.UriSchemeHttps))
            {
                transport = new HttpsTransportBindingElement();
            }
            else
            {
                transport = new HttpTransportBindingElement();
            }
            transport.ManualAddressing = true;
            transport.MaxReceivedMessageSize = ServiceUtility.MaxReceivedMessageSize;

            if (ServiceUtility.AuthenticationScheme != AuthenticationSchemes.None)
            {
                transport.AuthenticationScheme = ServiceUtility.AuthenticationScheme;
            }

            CustomBinding binding =
                new CustomBinding(
                    new BindingElement[] 
                    {
                        encoding,
                        transport
                    });

            ServiceEndpoint endpoint = new ServiceEndpoint(contract, binding, new EndpointAddress(address.OriginalString + "/" + this.Name));
            endpoint.Behaviors.Add(new DomainServiceWebHttpBehavior()
            {
                DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped
            });
            endpoint.Behaviors.Add(new SilverlightFaultBehavior());
            return endpoint;
        }
Пример #31
0
 protected HttpsTransportBindingElement(HttpsTransportBindingElement elementToBeCloned);
        public override XmlElement CreateWsspHttpsTokenAssertion(MetadataExporter exporter, HttpsTransportBindingElement httpsBinding)
        {
            XmlElement result = CreateWsspAssertion(HttpsTokenName);

            result.SetAttribute(RequireClientCertificateName, httpsBinding.RequireClientCertificate ? TrueName : FalseName);
            return(result);
        }
Пример #33
0
 internal static void EnableTransportSecurity(HttpsTransportBindingElement https, HttpTransportSecurity transportSecurity)
 {
     BasicHttpSecurity.EnableTransportSecurity(https, transportSecurity);
 }
Пример #34
0
 internal void ConfigureTransportProtectionOnly(HttpsTransportBindingElement https)
 {
     DisableAuthentication(https);
     https.RequireClientCertificate = false;
 }
Пример #35
0
        TransportBindingElement GetTransport()
        {
            HttpTransportBindingElement h;

            switch (Security.Mode)
            {
            case BasicHttpSecurityMode.Transport:
            case BasicHttpSecurityMode.TransportWithMessageCredential:
                h = new HttpsTransportBindingElement();
                break;

            default:
                h = new HttpTransportBindingElement();
                break;
            }

            h.AllowCookies           = AllowCookies;
            h.BypassProxyOnLocal     = BypassProxyOnLocal;
            h.HostNameComparisonMode = HostNameComparisonMode;
            h.MaxBufferPoolSize      = MaxBufferPoolSize;
            h.MaxBufferSize          = MaxBufferSize;
            h.MaxReceivedMessageSize = MaxReceivedMessageSize;
            h.ProxyAddress           = ProxyAddress;
            h.UseDefaultWebProxy     = UseDefaultWebProxy;
            h.TransferMode           = TransferMode;
#if NET_4_0
            h.ExtendedProtectionPolicy = Security.Transport.ExtendedProtectionPolicy;
#endif

            switch (Security.Transport.ClientCredentialType)
            {
            case HttpClientCredentialType.Basic:
                h.AuthenticationScheme = AuthenticationSchemes.Basic;
                break;

            case HttpClientCredentialType.Ntlm:
                h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
                break;

            case HttpClientCredentialType.Windows:
                h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
                break;

            case HttpClientCredentialType.Digest:
                h.AuthenticationScheme = AuthenticationSchemes.Digest;
                break;

            case HttpClientCredentialType.Certificate:
                switch (Security.Mode)
                {
                case BasicHttpSecurityMode.Transport:
                    (h as HttpsTransportBindingElement).RequireClientCertificate = true;
                    break;

                case BasicHttpSecurityMode.TransportCredentialOnly:
                    throw new InvalidOperationException("Certificate-based client authentication is not supported by 'TransportCredentialOnly' mode.");
                }
                break;
            }

            return(h);
        }
Пример #36
0
 public static HttpTransportBindingElement BuildHttpTransport(BindingSecurity securityType, MessageSizeQuotas quotas)
 {
     if (quotas == null)
     {
         quotas = new MessageSizeQuotas()
         {
             MaxBufferPoolSize      = 524288,
             MaxBufferSize          = 15000000,
             MaxReceivedMessageSize = 15000000
         };
     }
     if (securityType == BindingSecurity.None)
     {
         HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
         httpTransport.ManualAddressing          = false;
         httpTransport.AllowCookies              = false;
         httpTransport.AuthenticationScheme      = System.Net.AuthenticationSchemes.Anonymous;
         httpTransport.BypassProxyOnLocal        = false;
         httpTransport.HostNameComparisonMode    = HostNameComparisonMode.StrongWildcard;
         httpTransport.KeepAliveEnabled          = true;
         httpTransport.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
         httpTransport.Realm        = String.Empty;
         httpTransport.TransferMode = TransferMode.Buffered;
         httpTransport.UnsafeConnectionNtlmAuthentication = false;
         httpTransport.UseDefaultWebProxy     = false;
         httpTransport.MaxBufferPoolSize      = quotas.MaxBufferPoolSize;
         httpTransport.MaxReceivedMessageSize = quotas.MaxReceivedMessageSize;
         httpTransport.MaxBufferSize          = quotas.MaxBufferSize;
         //httpTransport.ExtendedProtectionPolicy.PolicyEnforcement = System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never;
         return(httpTransport);
     }
     else if (securityType == BindingSecurity.TLS || securityType == BindingSecurity.TLSWithCertificate || securityType == BindingSecurity.Credentials)
     {
         HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement();
         httpsTransportBindingElement.ManualAddressing       = false;
         httpsTransportBindingElement.MaxBufferPoolSize      = quotas.MaxBufferPoolSize;
         httpsTransportBindingElement.MaxReceivedMessageSize = quotas.MaxReceivedMessageSize;
         httpsTransportBindingElement.MaxBufferSize          = quotas.MaxBufferSize;
         httpsTransportBindingElement.AllowCookies           = false;
         httpsTransportBindingElement.BypassProxyOnLocal     = false;
         httpsTransportBindingElement.Realm            = string.Empty;
         httpsTransportBindingElement.KeepAliveEnabled = true;
         httpsTransportBindingElement.TransferMode     = TransferMode.Buffered;
         httpsTransportBindingElement.UnsafeConnectionNtlmAuthentication = false;
         httpsTransportBindingElement.UseDefaultWebProxy     = true;
         httpsTransportBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
         if (securityType == BindingSecurity.TLSWithCertificate)
         {
             httpsTransportBindingElement.AuthenticationScheme      = System.Net.AuthenticationSchemes.Digest;
             httpsTransportBindingElement.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Digest;
             httpsTransportBindingElement.RequireClientCertificate  = true;
         }
         else
         {
             httpsTransportBindingElement.AuthenticationScheme      = System.Net.AuthenticationSchemes.Anonymous;
             httpsTransportBindingElement.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
             httpsTransportBindingElement.RequireClientCertificate  = false;
         }
         return(httpsTransportBindingElement);
     }
     else
     {
         HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
         httpTransport.ManualAddressing          = false;
         httpTransport.MaxBufferPoolSize         = quotas.MaxBufferPoolSize;
         httpTransport.MaxReceivedMessageSize    = quotas.MaxReceivedMessageSize;
         httpTransport.MaxBufferSize             = quotas.MaxBufferSize;
         httpTransport.AllowCookies              = false;
         httpTransport.AuthenticationScheme      = System.Net.AuthenticationSchemes.Anonymous;
         httpTransport.BypassProxyOnLocal        = false;
         httpTransport.HostNameComparisonMode    = HostNameComparisonMode.StrongWildcard;
         httpTransport.KeepAliveEnabled          = true;
         httpTransport.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
         httpTransport.Realm        = String.Empty;
         httpTransport.TransferMode = TransferMode.Buffered;
         httpTransport.UnsafeConnectionNtlmAuthentication = false;
         httpTransport.UseDefaultWebProxy = false;
         //httpTransport.ExtendedProtectionPolicy.PolicyEnforcement = System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never;
         return(httpTransport);
     }
 }
Пример #37
0
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count > 3)
            {
                return(false);
            }

            SecurityBindingElement        securityElement = null;
            MessageEncodingBindingElement encoding        = null;
            HttpTransportBindingElement   transport       = null;

            foreach (BindingElement element in elements)
            {
                if (element is SecurityBindingElement)
                {
                    securityElement = element as SecurityBindingElement;
                }
                else if (element is TransportBindingElement)
                {
                    transport = element as HttpTransportBindingElement;
                }
                else if (element is MessageEncodingBindingElement)
                {
                    encoding = element as MessageEncodingBindingElement;
                }
                else
                {
                    return(false);
                }
            }

            HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement;

            if ((securityElement != null) && (httpsTransport != null) && (httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate))
            {
                return(false);
            }

            // process transport binding element
            UnifiedSecurityMode   mode;
            HttpTransportSecurity transportSecurity = new HttpTransportSecurity();

            if (!GetSecurityModeFromTransport(transport, transportSecurity, out mode))
            {
                return(false);
            }
            if (encoding == null)
            {
                return(false);
            }
            // BasicHttpBinding only supports Soap11
            if (!encoding.CheckEncodingVersion(EnvelopeVersion.Soap11))
            {
                return(false);
            }

            BasicHttpSecurity security;

            if (!HttpBindingBase.TryCreateSecurity(securityElement, mode, transportSecurity, out security))
            {
                return(false);
            }

            BasicHttpBinding basicHttpBinding = new BasicHttpBinding(security);

            basicHttpBinding.InitializeFrom(transport, encoding);

            // make sure all our defaults match
            if (!basicHttpBinding.IsBindingElementsMatch(transport, encoding))
            {
                return(false);
            }

            binding = basicHttpBinding;
            return(true);
        }
        protected HistoricalTrendProviderClient CreateServiceClient()
        {
            // todo find why this emits error here during async tasks

            _serviceUri = new UriBuilder("https", _configuration.Host, _configuration.Port, _configuration.Path).Uri;
            _userName   = _configuration.UserName;
            _password   = _configuration.Password;

            EndpointAddress endpoint = new EndpointAddress(_serviceUri);

            var security = SecurityBindingElement.CreateUserNameOverTransportBindingElement();

            security.EnableUnsecuredResponse = true;
            security.IncludeTimestamp        = false;
            security.MessageSecurityVersion  = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;

            CustomBinding binding = new CustomBinding();

            var mtomBinding = new MtomMessageEncodingBindingElement();

            mtomBinding.MaxBufferSize = 2147483647;
            binding.Elements.Add(mtomBinding);

            HttpTransportBindingElement httpTransport;

            //if ("http".Equals(_serviceUri.Scheme))
            //{
            //    //"http" supports the SoapUI MockService
            //    httpTransport = new HttpTransportBindingElement();
            //}
            //else
            //{
            binding.Elements.Add(security);
            httpTransport = new HttpsTransportBindingElement()
            {
                RequireClientCertificate = false
            };
            //}

            httpTransport.ManualAddressing          = false;
            httpTransport.AllowCookies              = false;
            httpTransport.AuthenticationScheme      = AuthenticationSchemes.Anonymous;
            httpTransport.BypassProxyOnLocal        = false;
            httpTransport.DecompressionEnabled      = true;
            httpTransport.HostNameComparisonMode    = HostNameComparisonMode.StrongWildcard;
            httpTransport.KeepAliveEnabled          = false;
            httpTransport.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous;
            httpTransport.Realm        = "";
            httpTransport.TransferMode = TransferMode.Buffered;
            httpTransport.UnsafeConnectionNtlmAuthentication = false;

            // Setting UseDefaultWebProxy to true slows down the first call to the web service
            httpTransport.UseDefaultWebProxy = false; // this differs from the WCF output

            // Default for the MaxReceivedMessageSize property is 65536 - too small in testing.
            httpTransport.MaxReceivedMessageSize = 2147483647;
            binding.Elements.Add(httpTransport);

            // SendTimeout – used to initialize the OperationTimeout, which governs the
            // whole process of sending a message, including receiving a reply message for
            // a request/reply service operation. This timeout also applies when sending
            // reply messages from a callback contract method.
            // PhasorPoint currently times out after 60 seconds.
            // Wait 30 extra seconds before declaring a timeout.
            // RequestTimeout should typically be 90 seconds.
            binding.SendTimeout = TimeSpan.FromSeconds(120);

            // Use a programmatic binding
            var serviceClient = new HistoricalTrendProviderClient(binding, endpoint);

            serviceClient.ClientCredentials.UserName.UserName = _userName;
            serviceClient.ClientCredentials.UserName.Password = _password;

            // validate cert by calling a function

            serviceClient.Endpoint.Behaviors.Add(_endpointBehavior);

            return(serviceClient);
        }
Пример #39
0
 internal static void ApplyTransportSecurity(HttpsTransportBindingElement transport, HttpTransportSecurity transportSecurity)
 {
     HttpTransportSecurity.ConfigureTransportProtectionAndAuthentication(transport, transportSecurity);
 }
Пример #40
0
        public override IChannelListener <TChannel> BuildChannelListener <TChannel>(BindingContext context)
        {
            HttpsTransportBindingElement ele = new HttpsTransportBindingElement();

            return(ele.BuildChannelListener <TChannel>(context));
        }
Пример #41
0
    public static void WebSocket_Https_Duplex_TextBuffered_KeepAlive()
    {
        TextMessageEncodingBindingElement textMessageEncodingBindingElement = null;
        HttpsTransportBindingElement      httpsTransportBindingElement      = null;
        CustomBinding   binding        = null;
        ClientReceiver  clientReceiver = null;
        InstanceContext context        = null;
        DuplexChannelFactory <IWSDuplexService> channelFactory = null;
        IWSDuplexService client = null;

        try
        {
            // *** SETUP *** \\
            textMessageEncodingBindingElement = new TextMessageEncodingBindingElement();
            httpsTransportBindingElement      = new HttpsTransportBindingElement()
            {
                MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB,
                MaxBufferSize          = ScenarioTestHelpers.SixtyFourMB
            };
            httpsTransportBindingElement.WebSocketSettings.TransportUsage    = WebSocketTransportUsage.Always;
            httpsTransportBindingElement.WebSocketSettings.KeepAliveInterval = TimeSpan.FromSeconds(2);
            binding = new CustomBinding(textMessageEncodingBindingElement, httpsTransportBindingElement);

            clientReceiver = new ClientReceiver();
            context        = new InstanceContext(clientReceiver);
            channelFactory = new DuplexChannelFactory <IWSDuplexService>(context, binding, new EndpointAddress(Endpoints.WebSocketHttpsDuplexTextBuffered_Address));
            client         = channelFactory.CreateChannel();

            // *** EXECUTE *** \\
            // Invoking UploadData
            client.UploadData(ScenarioTestHelpers.CreateInterestingString(123));

            // Invoking StartPushingData
            client.StartPushingData();
            Assert.True(clientReceiver.ReceiveDataInvoked.WaitOne(ScenarioTestHelpers.TestTimeout),
                        String.Format("Test case timeout was reached while waiting for the buffered response from the Service. Timeout was: {0}", ScenarioTestHelpers.TestTimeout));
            clientReceiver.ReceiveDataInvoked.Reset();
            // Invoking StopPushingData
            client.StopPushingData();
            Assert.True(clientReceiver.ReceiveDataCompleted.WaitOne(ScenarioTestHelpers.TestTimeout),
                        String.Format("Test case timeout was reached while waiting for the buffered response from the Service to be completed. Timeout was: {0}", ScenarioTestHelpers.TestTimeout));
            clientReceiver.ReceiveDataCompleted.Reset();

            // Getting results from server via callback.
            client.GetLog();
            Assert.True(clientReceiver.LogReceived.WaitOne(ScenarioTestHelpers.TestTimeout),
                        String.Format("Test case timeout was reached while waiting for the Logging from the Service to be received. Timeout was: {0}", ScenarioTestHelpers.TestTimeout));

            // *** VALIDATE *** \\
            Assert.True(clientReceiver.ServerLog.Count > 0,
                        "The logging done by the Server was not returned via the Callback.");

            // *** CLEANUP *** \\
            ((ICommunicationObject)client).Close();
            channelFactory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\ 
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory);
        }
    }
Пример #42
0
        // <snippet2>
        public override BindingElementCollection CreateBindingElements()
        {
            //SecurityBindingElement sbe = bec.Find<SecurityBindingElement>();
            BindingElementCollection bec = new BindingElementCollection();
            // By default http transport is used
            SecurityBindingElement securityBinding;
            BindingElement         transport;

            switch (assertion)
            {
            case WseSecurityAssertion.UsernameOverTransport:
                transport       = new HttpsTransportBindingElement();
                securityBinding = (TransportSecurityBindingElement)SecurityBindingElement.CreateUserNameOverTransportBindingElement();
                if (establishSecurityContext == true)
                {
                    throw new InvalidOperationException("Secure Conversation is not supported for this Security Assertion Type");
                }
                if (requireSignatureConfirmation == true)
                {
                    throw new InvalidOperationException("Signature Confirmation is not supported for this Security Assertion Type");
                }
                break;

            case WseSecurityAssertion.MutualCertificate10:
                transport       = new HttpTransportBindingElement();
                securityBinding = SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
                if (requireSignatureConfirmation == true)
                {
                    throw new InvalidOperationException("Signature Confirmation is not supported for this Security Assertion Type");
                }
                ((AsymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder = messageProtectionOrder;
                break;

            case WseSecurityAssertion.UsernameForCertificate:
                transport       = new HttpTransportBindingElement();
                securityBinding = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateUserNameForCertificateBindingElement();
                // We want signatureconfirmation on the bootstrap process
                // either for the application messages or for the RST/RSTR
                ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation;
                ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder       = messageProtectionOrder;
                break;

            case WseSecurityAssertion.AnonymousForCertificate:
                transport       = new HttpTransportBindingElement();
                securityBinding = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateAnonymousForCertificateBindingElement();
                ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation;
                ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder       = messageProtectionOrder;
                break;

            case WseSecurityAssertion.MutualCertificate11:
                transport       = new HttpTransportBindingElement();
                securityBinding = SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11);
                ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation;
                ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder       = messageProtectionOrder;
                break;

            case WseSecurityAssertion.Kerberos:
                transport       = new HttpTransportBindingElement();
                securityBinding = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateKerberosBindingElement();
                ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation;
                ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder       = messageProtectionOrder;
                break;

            default:
                throw new NotSupportedException("This supplied Wse security assertion is not supported");
            }
            //Set defaults for the security binding
            securityBinding.IncludeTimestamp = true;

            // Derived Keys
            // set the preference for derived keys before creating SecureConversationBindingElement
            securityBinding.SetKeyDerivation(requireDerivedKeys);

            //Secure Conversation
            if (establishSecurityContext == true)
            {
                SymmetricSecurityBindingElement secureconversation =
                    (SymmetricSecurityBindingElement)SymmetricSecurityBindingElement.CreateSecureConversationBindingElement(
                        securityBinding, false);
                // This is the default
                //secureconversation.DefaultProtectionLevel = ProtectionLevel.EncryptAndSign;

                //Set defaults for the secure conversation binding
                secureconversation.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256;
                // We do not want signature confirmation on the application level messages
                // when secure conversation is enabled.
                secureconversation.RequireSignatureConfirmation = false;
                secureconversation.MessageProtectionOrder       = messageProtectionOrder;
                secureconversation.SetKeyDerivation(requireDerivedKeys);
                securityBinding = secureconversation;
            }

            // Add the security binding to the binding collection
            bec.Add(securityBinding);

            // Add the message encoder.
            TextMessageEncodingBindingElement textelement = new TextMessageEncodingBindingElement();

            textelement.MessageVersion = MessageVersion.Soap11WSAddressingAugust2004;
            //These are the defaults required for WSE
            //textelement.MessageVersion = MessageVersion.Soap11Addressing1;
            //textelement.WriteEncoding = System.Text.Encoding.UTF8;
            bec.Add(textelement);

            // Add the transport
            bec.Add(transport);

            // return the binding elements
            return(bec);
        }
Пример #43
0
        /// <summary>
        /// Implement to include for exporting a custom policy assertion about bindings.
        /// </summary>
        /// <param name="exporter">The MetadataExporter that you can use to modify the exporting process.</param>
        /// <param name="context">The PolicyConversionContext that you can use to insert your custom policy assertion.</param>
        void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
        {
            HttpsTransportBindingElement httpsTBE = new HttpsTransportBindingElement();

            ((IPolicyExportExtension)httpsTBE).ExportPolicy(exporter, context);
        }
        internal static void ConfigureTransportProtectionAndAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpsTransportBindingElement httpsTransportBindingElement)
        {
            Debug.Assert(httpTransportSecurity != null, "httpTransportSecurity cannot be null");
            Debug.Assert(httpsTransportBindingElement != null, "httpsTransportBindingElement cannot be null");

            httpTransportSecurity.ConfigureAuthentication(httpsTransportBindingElement);
            httpsTransportBindingElement.RequireClientCertificate = httpTransportSecurity.ClientCredentialType == HttpClientCredentialType.Certificate;
        }
Пример #45
0
 internal void ConfigureTransportProtectionAndAuthentication(HttpsTransportBindingElement https)
 {
     ConfigureAuthentication(https);
     https.RequireClientCertificate = (_clientCredentialType == HttpClientCredentialType.Certificate);
 }
Пример #46
0
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count > 4)
            {
                return(false);
            }

            SecurityBindingElement        securityElement = null;
            MessageEncodingBindingElement encoding        = null;
            HttpTransportBindingElement   transport       = null;

            foreach (BindingElement element in elements)
            {
                if (element is SecurityBindingElement)
                {
                    securityElement = element as SecurityBindingElement;
                }
                else if (element is TransportBindingElement)
                {
                    transport = element as HttpTransportBindingElement;
                }
                else if (element is MessageEncodingBindingElement)
                {
                    encoding = element as MessageEncodingBindingElement;
                }
                else
                {
                    return(false);
                }
            }

            if (transport == null || transport.WebSocketSettings.TransportUsage != WebSocketTransportUsage.Always)
            {
                return(false);
            }

            HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement;

            if ((securityElement != null) && (httpsTransport != null) && (httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate))
            {
                return(false);
            }

            // process transport binding element
            UnifiedSecurityMode   mode;
            HttpTransportSecurity transportSecurity = new HttpTransportSecurity();

            if (!GetSecurityModeFromTransport(transport, transportSecurity, out mode))
            {
                return(false);
            }

            if (encoding == null)
            {
                return(false);
            }

            if (!(encoding is TextMessageEncodingBindingElement ||
                  encoding is BinaryMessageEncodingBindingElement))
            {
                return(false);
            }

            if (encoding.MessageVersion != MessageVersion.Soap12WSAddressing10)
            {
                return(false);
            }

            BasicHttpSecurity security;

            if (!TryCreateSecurity(securityElement, mode, transportSecurity, out security))
            {
                return(false);
            }

            NetHttpBinding netHttpBinding = new NetHttpBinding(security);

            netHttpBinding.InitializeFrom(transport, encoding);

            // make sure all our defaults match
            if (!netHttpBinding.IsBindingElementsMatch(transport, encoding))
            {
                return(false);
            }

            binding = netHttpBinding;
            return(true);
        }
Пример #47
0
 internal void EnableTransportSecurity(HttpsTransportBindingElement https)
 {
     _basicHttpSecurity.EnableTransportSecurity(https);
 }
Пример #48
0
 internal static void EnableTransportSecurity(HttpsTransportBindingElement https, HttpTransportSecurity transportSecurity)
 {
     HttpTransportSecurity.ConfigureTransportProtectionAndAuthentication(https, transportSecurity);
 }
        public override bool TryImportWsspHttpsTokenAssertion(MetadataImporter importer, ICollection <XmlElement> assertions, HttpsTransportBindingElement httpsBinding)
        {
            if (assertions == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertions");
            }

            bool       result;
            XmlElement assertion;

            if (TryImportWsspAssertion(assertions, HttpsTokenName, out assertion))
            {
                result = true;
                string v = assertion.GetAttribute(RequireClientCertificateName);
                try
                {
                    httpsBinding.RequireClientCertificate = XmlUtil.IsTrue(v);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    if (e is NullReferenceException)
                    {
                        throw;
                    }

                    importer.Errors.Add(new MetadataConversionError(SR.GetString(SR.UnsupportedBooleanAttribute, RequireClientCertificateName, e.Message), false));
                    result = false;
                }
            }
            else
            {
                result = false;
            }

            return(result);
        }
Пример #50
0
        public Models.imputacionCreditoConsulta consultarLimitativaCredito(Models.consultarLimitativaCreditoRequest request)
        {
            Models.imputacionCreditoConsulta ret = new Models.imputacionCreditoConsulta();

            log.Info(ServiceLogName + " - Ingreso");
            var b = _service.Endpoint.Binding as CustomBinding;

            log.Debug(ServiceLogName + " - Seteando variables de contexto.");
            string usuarioProxy = ConfigurationManager.AppSettings["CPA_Proxy_Usuario"];
            string passwdProxy  = ConfigurationManager.AppSettings["CPA_Proxy_Passwd"];
            string urlProxy     = ConfigurationManager.AppSettings["CPA_Proxy_URL"];
            string domainProxy  = ConfigurationManager.AppSettings["CPA_Proxy_Dominio"];
            string digitalMark  = ConfigurationManager.AppSettings["CERTI_DIGITAL_MARK"];

            string usuarioWS = ConfigurationManager.AppSettings["WS_Usuario"];
            string passwdWS  = string.Empty;

            #region Consulta Servicio Gestion Claves -o- Configuracion
            bool usarGClaves = false;
            bool.TryParse(ConfigurationManager.AppSettings["GCLaves_Habilitado"], out usarGClaves);

            if (usarGClaves)
            {
                log.Info("Obteniendo datos desde Gestion Claves");
                bool   gestionClavesSuccess = true;
                string gestionClavesMessage = string.Empty;

                try
                {
                    log.Info("Inicio Servicio Gestion Claves");
                    string gestionClavesEndpoint = ConfigurationManager.AppSettings["GClaves_Endpoint"];
                    _gestionClavesService.Endpoint.Address = new EndpointAddress(gestionClavesEndpoint);

                    string gcUser = ConfigurationManager.AppSettings["GCLaves_USU"];
                    string gcPass = ConfigurationManager.AppSettings["GCLaves_PSW"];

                    string key = ConfigurationManager.AppSettings["GClaves_EsidifPass"];

                    log.Info("Invocando al metodo ConsultarKey");
                    string result = _gestionClavesService.ConsultarKey(gcUser, gcPass, key);

                    if (!string.IsNullOrEmpty(result) && result.Length > 0)
                    {
                        log.Info("Invocacion a Gestion Claves Correcta");
                        passwdWS = result;
                    }
                    else
                    {
                        throw new Exception("El valor devuelto esta vacio");
                    }
                }
                catch (Exception ex)
                {
                    gestionClavesSuccess = false;
                    gestionClavesMessage = ex.Message;
                    log.Info("Fallo la invocacion a Gestion Claves: " + ex.Message);
                }

                if (!gestionClavesSuccess)
                {
                    throw new Exception(gestionClavesMessage);
                }
            }
            else
            {
                log.Info("Obteniendo datos desde la configuracion");
                passwdWS = ConfigurationManager.AppSettings["WS_Password"];
            }

            #endregion

            log.Debug(ServiceLogName + " - Seteando PROXY.");
            HttpsTransportBindingElement httpsTransport = new HttpsTransportBindingElement();
            httpsTransport.ProxyAddress           = new Uri(urlProxy);
            httpsTransport.UseDefaultWebProxy     = false;
            httpsTransport.BypassProxyOnLocal     = false;
            httpsTransport.MaxReceivedMessageSize = 2147483647;

            if (ConfigurationManager.AppSettings["CERTI_IGNORA_ERROR"] == "true")
            {
                log.Debug(ServiceLogName + " - IGNORA_ERROR_CERTI = true.");
                System.Net.ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidationCallback;
            }

            if (ConfigurationManager.AppSettings["CPA_Proxy_Credenciales"] == "true")
            {
                log.Debug(ServiceLogName + " - CPA_Proxy_Credenciales = true.");
                httpsTransport.ProxyAuthenticationScheme     = AuthenticationSchemes.Basic;
                _service.ClientCredentials.UserName.UserName = usuarioProxy;
                _service.ClientCredentials.UserName.Password = passwdProxy;
            }
            else
            {
                log.Debug(ServiceLogName + " - CPA_Proxy_Credenciales = false.");
                httpsTransport.ProxyAuthenticationScheme = AuthenticationSchemes.Ntlm;
            }

            b.Elements.Add(httpsTransport);

            if (ConfigurationManager.AppSettings["CERTI_APLICA"] == "true")
            {
                log.Debug(ServiceLogName + " - Cargando certificado X509.");
                _service.ClientCredentials.ClientCertificate.Certificate = Functions.GetClientCertificate(digitalMark);
                log.Debug(ServiceLogName + " - Certificado X509 cargado exitosamente.");
            }

            using (var scope = new OperationContextScope(_service.InnerChannel))
            {
                try
                {
                    log.Debug(ServiceLogName + " - Creando Bean");
                    var paramMecom = GenericClass <service.imputacionCreditoConsulta> .GenericMethod(); //service.imputacionCreditoConsulta.Create();

                    log.Debug(ServiceLogName + " - Mapeando a objeto MECON.");
                    Functions.CopyPropertiesTo(request.imputacionPresupuestariaCreditoIndicativa, paramMecom);

                    log.Debug(ServiceLogName + " - Armando header de autenticacion");
                    OperationContext.Current.OutgoingMessageHeaders.Add(new SecurityHeader("UsernameToken-1", usuarioWS, passwdWS));

                    _service.Endpoint.Address = new EndpointAddress(ConfigurationManager.AppSettings["WS_Endpoint"]);

                    var response = _service.consultarLimitativaCredito(paramMecom);

                    Functions.CopyPropertiesTo(response, ret);

                    return(ret);
                }
                catch (Exception ex)
                {
                    log.Error(ServiceLogName + " - Error en la ejecucion : " + ex.Message);
                    throw ex;
                }
            };
        }
Пример #51
0
 private void Initialize()
 {
     this.httpTransport      = new HttpTransportBindingElement();
     this.httpsTransport     = new HttpsTransportBindingElement();
     this.xmlRpcTextEncoding = new XmlRpcMessageEncodingBindingElement();
 }
Пример #52
0
        public override bool TryImportWsspHttpsTokenAssertion(MetadataImporter importer, ICollection <XmlElement> assertions, HttpsTransportBindingElement httpsBinding)
        {
            if (assertions == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertions");
            }

            bool       result = true;
            XmlElement assertion;

            if (TryImportWsspAssertion(assertions, HttpsTokenName, out assertion))
            {
                XmlElement policyElement = null;
                foreach (XmlNode node in assertion.ChildNodes)
                {
                    if (node is XmlElement && node.LocalName == WSSecurityPolicy.PolicyName && (node.NamespaceURI == WSSecurityPolicy.WspNamespace || node.NamespaceURI == WSSecurityPolicy.Wsp15Namespace))
                    {
                        policyElement = (XmlElement)node;
                        break;
                    }
                }

                if (policyElement != null)
                {
                    foreach (XmlNode node in policyElement.ChildNodes)
                    {
                        if (node is XmlElement && node.NamespaceURI == this.WsspNamespaceUri)
                        {
                            if (node.LocalName == WSSecurityPolicy.RequireClientCertificateName)
                            {
                                httpsBinding.RequireClientCertificate = true;
                            }
                            else if (node.LocalName == WSSecurityPolicy.HttpBasicAuthenticationName)
                            {
                                httpsBinding.AuthenticationScheme = AuthenticationSchemes.Basic;
                            }
                            else if (node.LocalName == WSSecurityPolicy.HttpDigestAuthenticationName)
                            {
                                httpsBinding.AuthenticationScheme = AuthenticationSchemes.Digest;
                            }
                        }
                    }
                }
            }
            else
            {
                result = false;
            }

            return(result);
        }
Пример #53
0
        void OnExplore(object sender, EventArgs e)
        {
            m_ExploreButton.Enabled = false;

            string mexAddress = m_MexAddressTextBox.Text;

            if (String.IsNullOrEmpty(mexAddress))
            {
                Debug.Assert(false, "Empty address");
            }
            m_MexTree.Nodes.Clear();
            DisplayBlankControl();

            SplashScreen splash = new SplashScreen(Resources.Progress);

            try
            {
                Uri address = new Uri(mexAddress);
                ServiceEndpointCollection endpoints = null;

                if (address.Scheme == "http")
                {
                    HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTP MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpBindingElement);
                    }
                    catch
                    {}
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "https")
                {
                    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTPS MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpsBindingElement);
                    }
                    catch
                    {
                    }
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpsGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpsGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpsBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "net.tcp")
                {
                    TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                    tcpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(tcpBindingElement);
                }
                if (address.Scheme == "net.pipe")
                {
                    NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                    ipcBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(ipcBindingElement);
                }
                ProcessMetaData(endpoints);
            }
            catch
            {
                m_MexTree.Nodes.Clear();

                m_Root = new ServiceNode(this, "Invalid Base Address", ServiceError, ServiceError);
                m_MexTree.Nodes.Add(m_Root);
                return;
            }
            finally
            {
                splash.Close();
                m_ExploreButton.Enabled = true;
            }
        }
Пример #54
0
    public static void WebSocket_Https_Duplex_BinaryStreamed()
    {
        BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = null;
        HttpsTransportBindingElement        httpsTransportBindingElement        = null;
        CustomBinding   binding        = null;
        ClientReceiver  clientReceiver = null;
        InstanceContext context        = null;
        DuplexChannelFactory <IWSDuplexService> channelFactory = null;
        IWSDuplexService     client       = null;
        FlowControlledStream uploadStream = null;

        try
        {
            // *** SETUP *** \\
            binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();
            httpsTransportBindingElement        = new HttpsTransportBindingElement();
            httpsTransportBindingElement.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;
            httpsTransportBindingElement.MaxReceivedMessageSize           = ScenarioTestHelpers.DefaultMaxReceivedMessageSize;
            httpsTransportBindingElement.MaxBufferSize = ScenarioTestHelpers.DefaultMaxReceivedMessageSize;
            httpsTransportBindingElement.TransferMode  = TransferMode.Streamed;
            binding = new CustomBinding(binaryMessageEncodingBindingElement, httpsTransportBindingElement);

            clientReceiver = new ClientReceiver();
            context        = new InstanceContext(clientReceiver);

            channelFactory = new DuplexChannelFactory <IWSDuplexService>(context, binding, Endpoints.WebSocketHttpsDuplexBinaryStreamed_Address);
            client         = channelFactory.CreateChannel();

            // *** EXECUTE *** \\
            using (Stream stream = client.DownloadStream())
            {
                int readResult;
                // Read from the stream, 1000 bytes at a time.
                byte[] buffer = new byte[1000];
                do
                {
                    readResult = stream.Read(buffer, 0, buffer.Length);
                }while (readResult != 0);
            }

            uploadStream = new FlowControlledStream();
            uploadStream.ReadThrottle   = TimeSpan.FromMilliseconds(500);
            uploadStream.StreamDuration = TimeSpan.FromSeconds(1);

            client.UploadStream(uploadStream);
            client.StartPushingStream();
            // Wait for the callback to get invoked before telling the service to stop streaming.
            // This ensures we can read from the stream on the callback while the NCL layer at the service
            // is still writing the bytes from the stream to the wire.
            // This will deadlock if the transfer mode is buffered because the callback will wait for the
            // stream, and the NCL layer will continue to buffer the stream until it reaches the end.

            Assert.True(clientReceiver.ReceiveStreamInvoked.WaitOne(ScenarioTestHelpers.TestTimeout), "Test case timeout was reached while waiting for the stream response from the Service.");
            clientReceiver.ReceiveStreamInvoked.Reset();

            // Upload the stream while we are downloading a different stream
            uploadStream = new FlowControlledStream();
            uploadStream.ReadThrottle   = TimeSpan.FromMilliseconds(500);
            uploadStream.StreamDuration = TimeSpan.FromSeconds(1);
            client.UploadStream(uploadStream);

            client.StopPushingStream();
            // Waiting on ReceiveStreamCompleted from the ClientReceiver.
            clientReceiver.ReceiveStreamCompleted.WaitOne();
            clientReceiver.ReceiveStreamCompleted.Reset();

            // *** VALIDATE *** \\
            // Validation is based on no exceptions being thrown.

            // *** CLEANUP *** \\
            ((ICommunicationObject)client).Close();
            channelFactory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory);
            clientReceiver.Dispose();
        }
    }
Пример #55
0
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if (String.IsNullOrEmpty(mexAddress))
            {
                Debug.Assert(false, "Empty address");
                return(null);
            }
            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints = null;

            if (address.Scheme == "http")
            {
                HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTP MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpBindingElement);
                }
                catch
                {}

                //Try over HTTP-GET
                if (endpoints == null)
                {
                    string httpGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpGetAddress += "?wsdl";
                    }
                    CustomBinding          binding   = new CustomBinding(httpBindingElement);
                    MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                    MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter       importer  = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "https")
            {
                HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTPS MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpsBindingElement);
                }
                catch
                {}

                //Try over HTTP-GET
                if (endpoints == null)
                {
                    string httpsGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpsGetAddress += "?wsdl";
                    }
                    CustomBinding          binding   = new CustomBinding(httpsBindingElement);
                    MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                    MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter       importer  = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "net.tcp")
            {
                TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                tcpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, tcpBindingElement);
            }
            if (address.Scheme == "net.pipe")
            {
                NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                ipcBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, ipcBindingElement);
            }
            return(Collection.ToArray(endpoints));
        }
Пример #56
0
        public override XmlElement CreateWsspHttpsTokenAssertion(MetadataExporter exporter, HttpsTransportBindingElement httpsBinding)
        {
            Fx.Assert(httpsBinding != null, "httpsBinding must not be null.");
            Fx.Assert(httpsBinding.AuthenticationScheme.IsSingleton(), "authenticationScheme must be a singleton value for security-mode TransportWithMessageCredential.");

            XmlElement result = CreateWsspAssertion(WSSecurityPolicy.HttpsTokenName);

            if (httpsBinding.RequireClientCertificate ||
                httpsBinding.AuthenticationScheme == AuthenticationSchemes.Basic ||
                httpsBinding.AuthenticationScheme == AuthenticationSchemes.Digest)
            {
                XmlElement policy = CreateWspPolicyWrapper(exporter);
                if (httpsBinding.RequireClientCertificate)
                {
                    policy.AppendChild(CreateWsspAssertion(WSSecurityPolicy.RequireClientCertificateName));
                }
                if (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Basic)
                {
                    policy.AppendChild(CreateWsspAssertion(WSSecurityPolicy.HttpBasicAuthenticationName));
                }
                else if (httpsBinding.AuthenticationScheme == AuthenticationSchemes.Digest)
                {
                    policy.AppendChild(CreateWsspAssertion(WSSecurityPolicy.HttpDigestAuthenticationName));
                }
                result.AppendChild(policy);
            }
            return(result);
        }
Пример #57
0
        public static FNCEWS40PortTypeClient ConfigureBinding(String user, String domain, String password, String uri)
        {
            BindingElementCollection bec = new BindingElementCollection();

            // Everything gets treated as if it is username credentials until
            //  right at the point of serialization.
            TransportSecurityBindingElement sbe = SecurityBindingElement.CreateUserNameOverTransportBindingElement();

            sbe.IncludeTimestamp       = false;
            sbe.AllowInsecureTransport = true;
            bec.Add(sbe);

            if (uri.IndexOf("SOAP") != -1)
            {
                // using the SOAP endpoint
                TextMessageEncodingBindingElement tme = new TextMessageEncodingBindingElement();
                tme.MessageVersion        = MessageVersion.Soap11;
                tme.ReaderQuotas.MaxDepth = 1024;
                tme.ReaderQuotas.MaxStringContentLength = 1024 * 1024;
                bec.Add(tme);
            }
            else
            {
                MtomMessageEncodingBindingElement mme = new MtomMessageEncodingBindingElement();
                mme.MessageVersion        = MessageVersion.Soap12;
                mme.ReaderQuotas.MaxDepth = 1024;
                mme.ReaderQuotas.MaxStringContentLength = 1024 * 1024;
                mme.MaxBufferSize = 2147483647;
                bec.Add(mme);
            }

            if (uri.IndexOf("https") != -1)
            {
                HttpsTransportBindingElement tbe = new HttpsTransportBindingElement();
                tbe.MaxReceivedMessageSize = 2147483647;
                tbe.MaxBufferSize          = 2147483647;
                bec.Add(tbe);
            }
            else
            {
                HttpTransportBindingElement httptbe = new HttpTransportBindingElement();
                httptbe.MaxReceivedMessageSize = 2147483647;
                httptbe.MaxBufferSize          = 2147483647;
                bec.Add(httptbe);
            }

            CustomBinding binding = new CustomBinding(bec);

            binding.ReceiveTimeout = new TimeSpan(TimeSpan.TicksPerDay);    // 100 nanonsecond units, make it 1 day
            binding.SendTimeout    = binding.ReceiveTimeout;

            EndpointAddress endpoint = new EndpointAddress(uri);

            _port = new FNCEWS40PortTypeClient(binding, endpoint);

            _port.ClientCredentials.UserName.UserName = user;
            _port.ClientCredentials.UserName.Password = password;

            // set up the Localization header, minus the locale. We assume
            //  the timezone cannot change between calls, but that the locale
            //  may.
            _localization          = new Localization();
            _localization.Timezone = GetTimezone();

            return(_port);
        }
Пример #58
0
 internal void EnableTransportSecurity(HttpsTransportBindingElement https)
 {
     this.transportSecurity.ConfigureTransportProtectionAndAuthentication(https);
 }
Пример #59
0
        static void FillBindingInfo(BindingElement bindingElement, ref IWmiInstance instance)
        {
            Fx.Assert(null != bindingElement, "");
            Fx.Assert(null != instance, "");

            if (bindingElement is IWmiInstanceProvider)
            {
                IWmiInstanceProvider instanceProvider = (IWmiInstanceProvider)bindingElement;
                instance = instance.NewInstance(instanceProvider.GetInstanceType());
                instanceProvider.FillInstance(instance);
                return;
            }

            Type elementType = AdministrationHelpers.GetServiceModelBaseType(bindingElement.GetType());

            if (null != elementType)
            {
                instance = instance.NewInstance(elementType.Name);
                if (bindingElement is TransportBindingElement)
                {
                    TransportBindingElement transport = (TransportBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.ManualAddressing, transport.ManualAddressing);
                    instance.SetProperty(AdministrationStrings.MaxReceivedMessageSize, transport.MaxReceivedMessageSize);
                    instance.SetProperty(AdministrationStrings.MaxBufferPoolSize, transport.MaxBufferPoolSize);
                    instance.SetProperty(AdministrationStrings.Scheme, transport.Scheme);

                    if (bindingElement is ConnectionOrientedTransportBindingElement)
                    {
                        ConnectionOrientedTransportBindingElement connectionOriented = (ConnectionOrientedTransportBindingElement)bindingElement;
                        instance.SetProperty(AdministrationStrings.ConnectionBufferSize, connectionOriented.ConnectionBufferSize);
                        instance.SetProperty(AdministrationStrings.HostNameComparisonMode, connectionOriented.HostNameComparisonMode.ToString());
                        instance.SetProperty(AdministrationStrings.ChannelInitializationTimeout, connectionOriented.ChannelInitializationTimeout);
                        instance.SetProperty(AdministrationStrings.MaxBufferSize, connectionOriented.MaxBufferSize);
                        instance.SetProperty(AdministrationStrings.MaxPendingConnections, connectionOriented.MaxPendingConnections);
                        instance.SetProperty(AdministrationStrings.MaxOutputDelay, connectionOriented.MaxOutputDelay);
                        instance.SetProperty(AdministrationStrings.MaxPendingAccepts, connectionOriented.MaxPendingAccepts);
                        instance.SetProperty(AdministrationStrings.TransferMode, connectionOriented.TransferMode.ToString());

                        if (bindingElement is TcpTransportBindingElement)
                        {
                            TcpTransportBindingElement tcp = (TcpTransportBindingElement)bindingElement;
                            instance.SetProperty(AdministrationStrings.ListenBacklog, tcp.ListenBacklog);
                            instance.SetProperty(AdministrationStrings.PortSharingEnabled, tcp.PortSharingEnabled);
                            instance.SetProperty(AdministrationStrings.TeredoEnabled, tcp.TeredoEnabled);

                            IWmiInstance connectionPool = instance.NewInstance(AdministrationStrings.TcpConnectionPoolSettings);
                            connectionPool.SetProperty(AdministrationStrings.GroupName, tcp.ConnectionPoolSettings.GroupName);
                            connectionPool.SetProperty(AdministrationStrings.IdleTimeout, tcp.ConnectionPoolSettings.IdleTimeout);
                            connectionPool.SetProperty(AdministrationStrings.LeaseTimeout, tcp.ConnectionPoolSettings.LeaseTimeout);
                            connectionPool.SetProperty(AdministrationStrings.MaxOutboundConnectionsPerEndpoint, tcp.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint);

                            instance.SetProperty(AdministrationStrings.ConnectionPoolSettings, connectionPool);

                            FillExtendedProtectionPolicy(instance, tcp.ExtendedProtectionPolicy);
                        }
                        else if (bindingElement is NamedPipeTransportBindingElement)
                        {
                            NamedPipeTransportBindingElement namedPipe = (NamedPipeTransportBindingElement)bindingElement;
                            IWmiInstance connectionPool = instance.NewInstance(AdministrationStrings.NamedPipeConnectionPoolSettings);

                            connectionPool.SetProperty(AdministrationStrings.GroupName, namedPipe.ConnectionPoolSettings.GroupName);
                            connectionPool.SetProperty(AdministrationStrings.IdleTimeout, namedPipe.ConnectionPoolSettings.IdleTimeout);
                            connectionPool.SetProperty(AdministrationStrings.MaxOutboundConnectionsPerEndpoint, namedPipe.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint);

                            instance.SetProperty(AdministrationStrings.ConnectionPoolSettings, connectionPool);
                        }
                    }
                    else if (bindingElement is HttpTransportBindingElement)
                    {
                        HttpTransportBindingElement http = (HttpTransportBindingElement)bindingElement;
                        instance.SetProperty(AdministrationStrings.AllowCookies, http.AllowCookies);
                        instance.SetProperty(AdministrationStrings.AuthenticationScheme, http.AuthenticationScheme.ToString());

                        instance.SetProperty(AdministrationStrings.BypassProxyOnLocal, http.BypassProxyOnLocal);
                        instance.SetProperty(AdministrationStrings.DecompressionEnabled, http.DecompressionEnabled);
                        instance.SetProperty(AdministrationStrings.HostNameComparisonMode, http.HostNameComparisonMode.ToString());
                        instance.SetProperty(AdministrationStrings.KeepAliveEnabled, http.KeepAliveEnabled);
                        instance.SetProperty(AdministrationStrings.MaxBufferSize, http.MaxBufferSize);
                        if (null != http.ProxyAddress)
                        {
                            instance.SetProperty(AdministrationStrings.ProxyAddress, http.ProxyAddress.AbsoluteUri.ToString());
                        }
                        instance.SetProperty(AdministrationStrings.ProxyAuthenticationScheme, http.ProxyAuthenticationScheme.ToString());
                        instance.SetProperty(AdministrationStrings.Realm, http.Realm);
                        instance.SetProperty(AdministrationStrings.TransferMode, http.TransferMode.ToString());
                        instance.SetProperty(AdministrationStrings.UnsafeConnectionNtlmAuthentication, http.UnsafeConnectionNtlmAuthentication);
                        instance.SetProperty(AdministrationStrings.UseDefaultWebProxy, http.UseDefaultWebProxy);

                        FillExtendedProtectionPolicy(instance, http.ExtendedProtectionPolicy);

                        if (bindingElement is HttpsTransportBindingElement)
                        {
                            HttpsTransportBindingElement https = (HttpsTransportBindingElement)bindingElement;
                            instance.SetProperty(AdministrationStrings.RequireClientCertificate, https.RequireClientCertificate);
                        }
                    }
                    else if (bindingElement is MsmqBindingElementBase)
                    {
                        MsmqBindingElementBase msmq = (MsmqBindingElementBase)bindingElement;

                        if (null != msmq.CustomDeadLetterQueue)
                        {
                            instance.SetProperty(AdministrationStrings.CustomDeadLetterQueue, msmq.CustomDeadLetterQueue.AbsoluteUri.ToString());
                        }
                        instance.SetProperty(AdministrationStrings.DeadLetterQueue, msmq.DeadLetterQueue);
                        instance.SetProperty(AdministrationStrings.Durable, msmq.Durable);
                        instance.SetProperty(AdministrationStrings.ExactlyOnce, msmq.ExactlyOnce);
                        instance.SetProperty(AdministrationStrings.MaxRetryCycles, msmq.MaxRetryCycles);
                        instance.SetProperty(AdministrationStrings.ReceiveContextEnabled, msmq.ReceiveContextEnabled);
                        instance.SetProperty(AdministrationStrings.ReceiveErrorHandling, msmq.ReceiveErrorHandling);
                        instance.SetProperty(AdministrationStrings.ReceiveRetryCount, msmq.ReceiveRetryCount);
                        instance.SetProperty(AdministrationStrings.RetryCycleDelay, msmq.RetryCycleDelay);
                        instance.SetProperty(AdministrationStrings.TimeToLive, msmq.TimeToLive);
                        instance.SetProperty(AdministrationStrings.UseSourceJournal, msmq.UseSourceJournal);
                        instance.SetProperty(AdministrationStrings.UseMsmqTracing, msmq.UseMsmqTracing);
                        instance.SetProperty(AdministrationStrings.ValidityDuration, msmq.ValidityDuration);

                        MsmqTransportBindingElement msmqTransport = msmq as MsmqTransportBindingElement;
                        if (null != msmqTransport)
                        {
                            instance.SetProperty(AdministrationStrings.MaxPoolSize, msmqTransport.MaxPoolSize);
                            instance.SetProperty(AdministrationStrings.QueueTransferProtocol, msmqTransport.QueueTransferProtocol);
                            instance.SetProperty(AdministrationStrings.UseActiveDirectory, msmqTransport.UseActiveDirectory);
                        }

                        MsmqIntegrationBindingElement msmqIntegration = msmq as MsmqIntegrationBindingElement;
                        if (null != msmqIntegration)
                        {
                            instance.SetProperty(AdministrationStrings.SerializationFormat, msmqIntegration.SerializationFormat.ToString());
                        }
                    }
#pragma warning disable 0618
                    else if (bindingElement is PeerTransportBindingElement)
                    {
                        PeerTransportBindingElement peer = (PeerTransportBindingElement)bindingElement;
                        instance.SetProperty(AdministrationStrings.ListenIPAddress, peer.ListenIPAddress);
                        instance.SetProperty(AdministrationStrings.Port, peer.Port);

                        IWmiInstance securitySettings = instance.NewInstance(AdministrationStrings.PeerSecuritySettings);
                        securitySettings.SetProperty(AdministrationStrings.PeerSecurityMode, peer.Security.Mode.ToString());
                        IWmiInstance transportSecuritySettings = securitySettings.NewInstance(AdministrationStrings.PeerTransportSecuritySettings);
                        transportSecuritySettings.SetProperty(AdministrationStrings.PeerTransportCredentialType, peer.Security.Transport.CredentialType.ToString());
                        securitySettings.SetProperty(AdministrationStrings.Transport, transportSecuritySettings);
                        instance.SetProperty(AdministrationStrings.Security, securitySettings);
                    }
                }
                else if (bindingElement is PeerResolverBindingElement)
                {
                    PeerResolverBindingElement baseResolver = (PeerResolverBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.ReferralPolicy, baseResolver.ReferralPolicy.ToString());
                    if (bindingElement is PeerCustomResolverBindingElement)
                    {
                        PeerCustomResolverBindingElement specificElement = (PeerCustomResolverBindingElement)bindingElement;
                        if (specificElement.Address != null)
                        {
                            instance.SetProperty(AdministrationStrings.Address, specificElement.Address.ToString());
                        }
                        if (specificElement.Binding != null)
                        {
                            instance.SetProperty(AdministrationStrings.Binding, specificElement.Binding.ToString());
                        }
                    }
                }
#pragma warning restore 0618
                else if (bindingElement is ReliableSessionBindingElement)
                {
                    ReliableSessionBindingElement specificElement = (ReliableSessionBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.AcknowledgementInterval, specificElement.AcknowledgementInterval);
                    instance.SetProperty(AdministrationStrings.FlowControlEnabled, specificElement.FlowControlEnabled);
                    instance.SetProperty(AdministrationStrings.InactivityTimeout, specificElement.InactivityTimeout);
                    instance.SetProperty(AdministrationStrings.MaxPendingChannels, specificElement.MaxPendingChannels);
                    instance.SetProperty(AdministrationStrings.MaxRetryCount, specificElement.MaxRetryCount);
                    instance.SetProperty(AdministrationStrings.MaxTransferWindowSize, specificElement.MaxTransferWindowSize);
                    instance.SetProperty(AdministrationStrings.Ordered, specificElement.Ordered);
                    instance.SetProperty(AdministrationStrings.ReliableMessagingVersion, specificElement.ReliableMessagingVersion.ToString());
                }
                else if (bindingElement is SecurityBindingElement)
                {
                    SecurityBindingElement specificElement = (SecurityBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.AllowInsecureTransport, specificElement.AllowInsecureTransport);
                    instance.SetProperty(AdministrationStrings.DefaultAlgorithmSuite, specificElement.DefaultAlgorithmSuite.ToString());
                    instance.SetProperty(AdministrationStrings.EnableUnsecuredResponse, specificElement.EnableUnsecuredResponse);
                    instance.SetProperty(AdministrationStrings.IncludeTimestamp, specificElement.IncludeTimestamp);
                    instance.SetProperty(AdministrationStrings.KeyEntropyMode, specificElement.KeyEntropyMode.ToString());
                    instance.SetProperty(AdministrationStrings.SecurityHeaderLayout, specificElement.SecurityHeaderLayout.ToString());
                    instance.SetProperty(AdministrationStrings.MessageSecurityVersion, specificElement.MessageSecurityVersion.ToString());

                    IWmiInstance localServiceSecuritySettings = instance.NewInstance(AdministrationStrings.LocalServiceSecuritySettings);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.DetectReplays, specificElement.LocalServiceSettings.DetectReplays);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.InactivityTimeout, specificElement.LocalServiceSettings.InactivityTimeout);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.IssuedCookieLifetime, specificElement.LocalServiceSettings.IssuedCookieLifetime);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxCachedCookies, specificElement.LocalServiceSettings.MaxCachedCookies);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxClockSkew, specificElement.LocalServiceSettings.MaxClockSkew);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxPendingSessions, specificElement.LocalServiceSettings.MaxPendingSessions);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxStatefulNegotiations, specificElement.LocalServiceSettings.MaxStatefulNegotiations);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.NegotiationTimeout, specificElement.LocalServiceSettings.NegotiationTimeout);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.ReconnectTransportOnFailure, specificElement.LocalServiceSettings.ReconnectTransportOnFailure);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.ReplayCacheSize, specificElement.LocalServiceSettings.ReplayCacheSize);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.ReplayWindow, specificElement.LocalServiceSettings.ReplayWindow);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.SessionKeyRenewalInterval, specificElement.LocalServiceSettings.SessionKeyRenewalInterval);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.SessionKeyRolloverInterval, specificElement.LocalServiceSettings.SessionKeyRolloverInterval);
                    localServiceSecuritySettings.SetProperty(AdministrationStrings.TimestampValidityDuration, specificElement.LocalServiceSettings.TimestampValidityDuration);
                    instance.SetProperty(AdministrationStrings.LocalServiceSecuritySettings, localServiceSecuritySettings);

                    if (bindingElement is AsymmetricSecurityBindingElement)
                    {
                        AsymmetricSecurityBindingElement specificElement1 = (AsymmetricSecurityBindingElement)bindingElement;

                        instance.SetProperty(AdministrationStrings.MessageProtectionOrder, specificElement1.MessageProtectionOrder.ToString());
                        instance.SetProperty(AdministrationStrings.RequireSignatureConfirmation, specificElement1.RequireSignatureConfirmation);
                    }
                    else if (bindingElement is SymmetricSecurityBindingElement)
                    {
                        SymmetricSecurityBindingElement specificElement1 = (SymmetricSecurityBindingElement)bindingElement;

                        instance.SetProperty(AdministrationStrings.MessageProtectionOrder, specificElement1.MessageProtectionOrder.ToString());
                        instance.SetProperty(AdministrationStrings.RequireSignatureConfirmation, specificElement1.RequireSignatureConfirmation);
                    }
                }
                else if (bindingElement is WindowsStreamSecurityBindingElement)
                {
                    WindowsStreamSecurityBindingElement specificElement
                        = (WindowsStreamSecurityBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.ProtectionLevel, specificElement.ProtectionLevel.ToString());
                }
                else if (bindingElement is SslStreamSecurityBindingElement)
                {
                    SslStreamSecurityBindingElement specificElement = (SslStreamSecurityBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.RequireClientCertificate, specificElement.RequireClientCertificate);
                }
                else if (bindingElement is CompositeDuplexBindingElement)
                {
                    CompositeDuplexBindingElement specificElement = (CompositeDuplexBindingElement)bindingElement;
                    if (specificElement.ClientBaseAddress != null)
                    {
                        instance.SetProperty(AdministrationStrings.ClientBaseAddress, specificElement.ClientBaseAddress.AbsoluteUri);
                    }
                }
                else if (bindingElement is OneWayBindingElement)
                {
                    OneWayBindingElement oneWay = (OneWayBindingElement)bindingElement;
                    IWmiInstance         channelPoolSettings = instance.NewInstance(AdministrationStrings.ChannelPoolSettings);
                    channelPoolSettings.SetProperty(AdministrationStrings.IdleTimeout, oneWay.ChannelPoolSettings.IdleTimeout);
                    channelPoolSettings.SetProperty(AdministrationStrings.LeaseTimeout, oneWay.ChannelPoolSettings.LeaseTimeout);
                    channelPoolSettings.SetProperty(AdministrationStrings.MaxOutboundChannelsPerEndpoint, oneWay.ChannelPoolSettings.MaxOutboundChannelsPerEndpoint);
                    instance.SetProperty(AdministrationStrings.ChannelPoolSettings, channelPoolSettings);
                    instance.SetProperty(AdministrationStrings.PacketRoutable, oneWay.PacketRoutable);
                    instance.SetProperty(AdministrationStrings.MaxAcceptedChannels, oneWay.MaxAcceptedChannels);
                }
                else if (bindingElement is MessageEncodingBindingElement)
                {
                    MessageEncodingBindingElement encodingElement = (MessageEncodingBindingElement)bindingElement;

                    instance.SetProperty(AdministrationStrings.MessageVersion, encodingElement.MessageVersion.ToString());

                    if (bindingElement is BinaryMessageEncodingBindingElement)
                    {
                        BinaryMessageEncodingBindingElement specificElement = (BinaryMessageEncodingBindingElement)bindingElement;
                        instance.SetProperty(AdministrationStrings.MaxSessionSize, specificElement.MaxSessionSize);
                        instance.SetProperty(AdministrationStrings.MaxReadPoolSize, specificElement.MaxReadPoolSize);
                        instance.SetProperty(AdministrationStrings.MaxWritePoolSize, specificElement.MaxWritePoolSize);
                        if (null != specificElement.ReaderQuotas)
                        {
                            FillReaderQuotas(instance, specificElement.ReaderQuotas);
                        }
                        instance.SetProperty(AdministrationStrings.CompressionFormat, specificElement.CompressionFormat.ToString());
                    }
                    else if (bindingElement is TextMessageEncodingBindingElement)
                    {
                        TextMessageEncodingBindingElement specificElement = (TextMessageEncodingBindingElement)bindingElement;
                        instance.SetProperty(AdministrationStrings.Encoding, specificElement.WriteEncoding.WebName);
                        instance.SetProperty(AdministrationStrings.MaxReadPoolSize, specificElement.MaxReadPoolSize);
                        instance.SetProperty(AdministrationStrings.MaxWritePoolSize, specificElement.MaxWritePoolSize);
                        if (null != specificElement.ReaderQuotas)
                        {
                            FillReaderQuotas(instance, specificElement.ReaderQuotas);
                        }
                    }
                    else if (bindingElement is MtomMessageEncodingBindingElement)
                    {
                        MtomMessageEncodingBindingElement specificElement = (MtomMessageEncodingBindingElement)bindingElement;
                        instance.SetProperty(AdministrationStrings.Encoding, specificElement.WriteEncoding.WebName);
                        instance.SetProperty(AdministrationStrings.MessageVersion, specificElement.MessageVersion.ToString());
                        instance.SetProperty(AdministrationStrings.MaxReadPoolSize, specificElement.MaxReadPoolSize);
                        instance.SetProperty(AdministrationStrings.MaxWritePoolSize, specificElement.MaxWritePoolSize);
                        if (null != specificElement.ReaderQuotas)
                        {
                            FillReaderQuotas(instance, specificElement.ReaderQuotas);
                        }
                    }
                }
                else if (bindingElement is TransactionFlowBindingElement)
                {
                    TransactionFlowBindingElement specificElement = (TransactionFlowBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.TransactionFlow, specificElement.Transactions);
                    instance.SetProperty(AdministrationStrings.TransactionProtocol, specificElement.TransactionProtocol.ToString());
                    instance.SetProperty(AdministrationStrings.AllowWildcardAction, specificElement.AllowWildcardAction);
                }
                else if (bindingElement is PrivacyNoticeBindingElement)
                {
                    PrivacyNoticeBindingElement specificElement = (PrivacyNoticeBindingElement)bindingElement;
                    instance.SetProperty(AdministrationStrings.Url, specificElement.Url.ToString());
                    instance.SetProperty(AdministrationStrings.PrivacyNoticeVersion, specificElement.Version);
                }
            }
        }
Пример #60
0
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if (string.IsNullOrWhiteSpace(mexAddress))
            {
                throw new ArgumentException("mexAddress");
            }

            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints      = null;
            BindingElement            bindingElement = null;

            //Try over HTTP-GET first
            if (address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps)
            {
                string getAddress = mexAddress;
                if (mexAddress.EndsWith("?wsdl") == false)
                {
                    getAddress += "?wsdl";
                }
                if (address.Scheme == Uri.UriSchemeHttp)
                {
                    HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                    bindingElement = httpBindingElement;
                }
                else
                {
                    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                    bindingElement = httpsBindingElement;
                }
                CustomBinding binding = new CustomBinding(bindingElement);

                MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
                MetadataSet            metadata  = mexClient.GetMetadata(new Uri(getAddress), MetadataExchangeClientMode.HttpGet);
                MetadataImporter       importer  = new WsdlImporter(metadata);
                endpoints = importer.ImportAllEndpoints();
                return(endpoints.ToArray());
            }

            //Try MEX endpoint:

            if (address.Scheme == Uri.UriSchemeHttp)
            {
                bindingElement = new HttpTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeHttps)
            {
                bindingElement = new HttpsTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeNetTcp)
            {
                bindingElement = new TcpTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeNetPipe)
            {
                bindingElement = new NamedPipeTransportBindingElement();
            }

            endpoints = QueryMexEndpoint(mexAddress, bindingElement);
            return(endpoints.ToArray());
        }