Example #1
0
 private TextMessageEncodingBindingElement(TextMessageEncodingBindingElement elementToBeCloned) : base(elementToBeCloned)
 {
     this.maxReadPoolSize  = elementToBeCloned.maxReadPoolSize;
     this.maxWritePoolSize = elementToBeCloned.maxWritePoolSize;
     this.readerQuotas     = new XmlDictionaryReaderQuotas();
     elementToBeCloned.readerQuotas.CopyTo(this.readerQuotas);
     this.writeEncoding  = elementToBeCloned.writeEncoding;
     this.messageVersion = elementToBeCloned.messageVersion;
 }
Example #2
0
 private TextMessageEncodingBindingElement(TextMessageEncodingBindingElement elementToBeCloned)
     : base(elementToBeCloned)
 {
     _maxReadPoolSize  = elementToBeCloned._maxReadPoolSize;
     _maxWritePoolSize = elementToBeCloned._maxWritePoolSize;
     _readerQuotas     = new XmlDictionaryReaderQuotas();
     elementToBeCloned._readerQuotas.CopyTo(_readerQuotas);
     _writeEncoding  = elementToBeCloned._writeEncoding;
     _messageVersion = elementToBeCloned._messageVersion;
 }
		public void BuildChannelFactory ()
		{
			CustomBinding cb = new CustomBinding (
				new HttpTransportBindingElement ());
			BindingContext ctx = new BindingContext (
				cb, new BindingParameterCollection ());
			Element el = new Element ();
			IChannelFactory<IRequestChannel> cf =
				el.BuildChannelFactory<IRequestChannel> (ctx);
		}
		public void CanBuildChannelFactory ()
		{
			CustomBinding cb = new CustomBinding (
				new HttpTransportBindingElement ());
			BindingContext ctx = new BindingContext (
				cb, new BindingParameterCollection ());
			Element el = new Element ();
			Assert.IsTrue (el.CanBuildChannelFactory<IRequestChannel> (ctx), "#1");
			Assert.IsFalse (el.CanBuildChannelFactory<IRequestSessionChannel> (ctx), "#2");
		}
		public void DefaultValues ()
		{
			Element el = new Element ();
			Assert.AreEqual (64, el.MaxReadPoolSize, "#1");
			Assert.AreEqual (16, el.MaxWritePoolSize, "#2");
			Assert.AreEqual (MessageVersion.Default, el.MessageVersion, "#3");
			// FIXME: test ReaderQuotas

			Assert.AreEqual (Encoding.UTF8, el.WriteEncoding, "#4");
		}
Example #6
0
        internal override bool IsMatch(BindingElement b)
        {
            if (!base.IsMatch(b))
            {
                return(false);
            }

            TextMessageEncodingBindingElement text = b as TextMessageEncodingBindingElement;

            if (text == null)
            {
                return(false);
            }
            if (_maxReadPoolSize != text.MaxReadPoolSize)
            {
                return(false);
            }
            if (_maxWritePoolSize != text.MaxWritePoolSize)
            {
                return(false);
            }

            // compare XmlDictionaryReaderQuotas
            if (_readerQuotas.MaxStringContentLength != text.ReaderQuotas.MaxStringContentLength)
            {
                return(false);
            }
            if (_readerQuotas.MaxArrayLength != text.ReaderQuotas.MaxArrayLength)
            {
                return(false);
            }
            if (_readerQuotas.MaxBytesPerRead != text.ReaderQuotas.MaxBytesPerRead)
            {
                return(false);
            }
            if (_readerQuotas.MaxDepth != text.ReaderQuotas.MaxDepth)
            {
                return(false);
            }
            if (_readerQuotas.MaxNameTableCharCount != text.ReaderQuotas.MaxNameTableCharCount)
            {
                return(false);
            }

            if (this.WriteEncoding.WebName != text.WriteEncoding.WebName)
            {
                return(false);
            }
            if (!this.MessageVersion.IsMatch(text.MessageVersion))
            {
                return(false);
            }

            return(true);
        }
        private TextMessageEncodingBindingElement(
            TextMessageEncodingBindingElement source)
        {
            version             = source.version;
            max_read_pool_size  = source.max_read_pool_size;
            max_write_pool_size = source.max_write_pool_size;
            encoding            = source.encoding;

            quotas = new XmlDictionaryReaderQuotas();
            source.quotas.CopyTo(quotas);
        }
        public void CanBuildChannelFactory()
        {
            CustomBinding cb = new CustomBinding(
                new HttpTransportBindingElement());
            BindingContext ctx = new BindingContext(
                cb, new BindingParameterCollection());
            Element el = new Element();

            Assert.IsTrue(el.CanBuildChannelFactory <IRequestChannel> (ctx), "#1");
            Assert.IsFalse(el.CanBuildChannelFactory <IRequestSessionChannel> (ctx), "#2");
        }
        public void DefaultValues()
        {
            Element el = new Element();

            Assert.AreEqual(64, el.MaxReadPoolSize, "#1");
            Assert.AreEqual(16, el.MaxWritePoolSize, "#2");
            Assert.AreEqual(MessageVersion.Default, el.MessageVersion, "#3");
            // FIXME: test ReaderQuotas

            Assert.AreEqual(Encoding.UTF8, el.WriteEncoding, "#4");
        }
        private MessageEncodingBindingElement FindMessageEncodingBindingElement(BindingElementCollection bindingElements, out bool createdNew)
        {
            createdNew = false;
            MessageEncodingBindingElement encodingBindingElement = bindingElements.Find <MessageEncodingBindingElement>();

            if (encodingBindingElement == null)
            {
                createdNew             = true;
                encodingBindingElement = new TextMessageEncodingBindingElement();
            }
            return(encodingBindingElement);
        }
        void IWsdlImportExtension.ImportEndpoint(WsdlImporter importer, WsdlEndpointConversionContext context)
        {
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

#pragma warning suppress 56506 // Microsoft, these properties cannot be null in this context
            if (context.Endpoint.Binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context.Endpoint.Binding");
            }

            BindingElementCollection          bindingElements = GetBindingElements(context);
            MessageEncodingBindingElement     messageEncodingBindingElement = bindingElements.Find <MessageEncodingBindingElement>();
            TextMessageEncodingBindingElement textEncodingBindingElement    = messageEncodingBindingElement as TextMessageEncodingBindingElement;

            if (messageEncodingBindingElement != null)
            {
                Type elementType = messageEncodingBindingElement.GetType();
                if (elementType != typeof(TextMessageEncodingBindingElement) &&
                    elementType != typeof(BinaryMessageEncodingBindingElement) &&
                    elementType != typeof(MtomMessageEncodingBindingElement))
                {
                    return;
                }
            }

            EnsureMessageEncoding(context, messageEncodingBindingElement);

            foreach (OperationBinding wsdlOperationBinding in context.WsdlBinding.Operations)
            {
                OperationDescription operation = context.GetOperationDescription(wsdlOperationBinding);

                for (int i = 0; i < operation.Messages.Count; i++)
                {
                    MessageDescription message            = operation.Messages[i];
                    MessageBinding     wsdlMessageBinding = context.GetMessageBinding(message);
                    ImportMessageSoapAction(context.ContractConversionContext, message, wsdlMessageBinding, i != 0 /*isResponse*/);
                }

                foreach (FaultDescription fault in operation.Faults)
                {
                    FaultBinding wsdlFaultBinding = context.GetFaultBinding(fault);
                    if (wsdlFaultBinding != null)
                    {
                        ImportFaultSoapAction(context.ContractConversionContext, fault, wsdlFaultBinding);
                    }
                }
            }
        }
        void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
        {
            if (exporter == null)
            {
                throw FxTrace.Exception.ArgumentNull("exporter");
            }

            if (context == null)
            {
                throw FxTrace.Exception.ArgumentNull("context");
            }

            MessageEncodingBindingElement encodingBindingElement = context.BindingElements.Find <MessageEncodingBindingElement>();

            if (encodingBindingElement == null)
            {
                encodingBindingElement = new TextMessageEncodingBindingElement();
            }

            WsdlExporter.WSAddressingHelper.AddWSAddressingAssertion(exporter, context, encodingBindingElement.MessageVersion.Addressing);

            UdpTransportBindingElementPolicy.ExportRetransmissionEnabledAssertion(this, context.GetBindingAssertions());
        }
Example #13
0
        bool ImportBasicHttpBinding(
            WsdlImporter importer, WsdlEndpointConversionContext context,
            CustomBinding custom, WS.SoapBinding soap)
        {
            TransportBindingElement           transportElement = null;
            MtomMessageEncodingBindingElement mtomElement      = null;
            TextMessageEncodingBindingElement textElement      = null;
            bool foundUnknownElement = false;

            foreach (var element in custom.Elements)
            {
                if (element is TransportBindingElement)
                {
                    transportElement = (TransportBindingElement)element;
                }
                else if (element is MtomMessageEncodingBindingElement)
                {
                    mtomElement = (MtomMessageEncodingBindingElement)element;
                }
                else if (element is TextMessageEncodingBindingElement)
                {
                    textElement = (TextMessageEncodingBindingElement)element;
                }
                else
                {
                    importer.AddWarning(
                        "Found unknown binding element `{0}' while attempting " +
                        "to import binding `{0}'.", element.GetType(),
                        custom.Name);
                    foundUnknownElement = true;
                }
            }

            if (foundUnknownElement)
            {
                return(false);
            }

            if ((mtomElement != null) && (textElement != null))
            {
                // FIXME: Should never happen
                importer.AddWarning(
                    "Found both MtomMessageEncodingBindingElement and " +
                    "TextMessageEncodingBindingElement while attempting to " +
                    "import binding `{0}'.", custom.Name);
                return(false);
            }

            BasicHttpBinding      httpBinding;
            AuthenticationSchemes authScheme;

            /*
             * FIXME: Maybe make the BasicHttpBinding use the transport element
             * that we created with the TransportBindingElementImporter ?
             *
             * There seems to be no public API to do that, so maybe add a private .ctor ?
             *
             */

            var httpsTransport = transportElement as HttpsTransportBindingElement;
            var httpTransport  = transportElement as HttpTransportBindingElement;

            if (httpsTransport != null)
            {
                httpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                authScheme  = httpsTransport.AuthenticationScheme;
            }
            else if (httpTransport != null)
            {
                authScheme = httpTransport.AuthenticationScheme;
                if ((authScheme != AuthenticationSchemes.None) &&
                    (authScheme != AuthenticationSchemes.Anonymous))
                {
                    httpBinding = new BasicHttpBinding(
                        BasicHttpSecurityMode.TransportCredentialOnly);
                }
                else
                {
                    httpBinding = new BasicHttpBinding();
                }
            }
            else
            {
                httpBinding = new BasicHttpBinding();
                authScheme  = AuthenticationSchemes.Anonymous;
            }

            if (mtomElement != null)
            {
                httpBinding.MessageEncoding = WSMessageEncoding.Mtom;
            }
            else if (textElement != null)
            {
                httpBinding.MessageEncoding = WSMessageEncoding.Text;
            }
            else
            {
                importer.AddWarning(
                    "Found neither MtomMessageEncodingBindingElement nor " +
                    "TextMessageEncodingBindingElement while attempting to " +
                    "import binding `{0}'.", custom.Name);
                return(false);
            }

            httpBinding.Name      = context.Endpoint.Binding.Name;
            httpBinding.Namespace = context.Endpoint.Binding.Namespace;

            switch (authScheme)
            {
            case AuthenticationSchemes.None:
            case AuthenticationSchemes.Anonymous:
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                break;

            case AuthenticationSchemes.Basic:
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                break;

            case AuthenticationSchemes.Digest:
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest;
                break;

            case AuthenticationSchemes.Ntlm:
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
                break;

            case AuthenticationSchemes.Negotiate:
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                break;

            default:
                importer.AddWarning("Invalid auth scheme: {0}", authScheme);
                return(false);
            }

            if ((httpsTransport != null) && httpsTransport.RequireClientCertificate)
            {
                if (httpBinding.Security.Transport.ClientCredentialType != HttpClientCredentialType.None)
                {
                    importer.AddWarning("Cannot use both client certificate and explicit auth type.");
                    return(false);
                }
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
            }

            context.Endpoint.Binding = httpBinding;
            return(true);
        }
Example #14
0
        static void Main(string[] args)
        {
            // Setup Log4Net configuration by loading it from configuration file
            // log4net is not necessary and is only being used for demonstration
            XmlConfigurator.Configure();

            // To ensure that the WSP is up and running.
            Thread.Sleep(1000);

            // Retrieve token
            IStsTokenService stsTokenService =
                new StsTokenServiceCache(
                    TokenServiceConfigurationFactory.CreateConfiguration()
                    );
            var securityToken = stsTokenService.GetToken();

            // Call WSP with token
            var hostname        = "https://localhost:8443/HelloWorld/services/helloworld";
            var customBinding   = new Channels.CustomBinding();
            var endpointAddress = new System.ServiceModel.EndpointAddress(
                new Uri(hostname),
                System.ServiceModel.EndpointIdentity.CreateDnsIdentity(
                    //"wsp.oioidws-net.dk TEST (funktionscertifikat)"
                    "eID JAVA test (funktionscertifikat)"
                    ),
                new Channels.AddressHeader[] { }
                );

            var asymmetric =
                new Channels.AsymmetricSecurityBindingElement
                (
                    new SecurityTokens.X509SecurityTokenParameters(
                        SecurityTokens.X509KeyIdentifierClauseType.Any,
                        SecurityTokens.SecurityTokenInclusionMode.AlwaysToInitiator
                        ),
                    new Soap.StrCustomization.CustomizedIssuedSecurityTokenParameters(
                        "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
                        )
            {
                UseStrTransform = true
            }
                )
            {
                AllowSerializedSigningTokenOnReply = true,
                ProtectTokens = true
            };

            asymmetric.SetKeyDerivation(false);
            var messageEncoding =
                new Channels.TextMessageEncodingBindingElement
            {
                MessageVersion =
                    Channels.MessageVersion.Soap12WSAddressing10
            };
            var transport =
                (hostname.ToLower().StartsWith("https://"))
                    ? new Channels.HttpsTransportBindingElement()
                    : new Channels.HttpTransportBindingElement();

            customBinding.Elements.Add(asymmetric);
            customBinding.Elements.Add(messageEncoding);
            customBinding.Elements.Add(transport);

            System.ServiceModel.ChannelFactory <HelloWorldPortType> factory =
                new System.ServiceModel.ChannelFactory <HelloWorldPortType>(
                    customBinding, endpointAddress
                    );
            factory.Credentials.UseIdentityConfiguration = true;
            factory.Credentials.ServiceCertificate.SetScopedCertificate(
                X509Certificates.StoreLocation.LocalMachine,
                X509Certificates.StoreName.My,
                X509Certificates.X509FindType.FindByThumbprint,
                //"1F0830937C74B0567D6B05C07B6155059D9B10C7",
                "85398FCF737FB76F554C6F2422CC39D3A35EC26F",
                new Uri(hostname)
                );
            factory.Endpoint.Behaviors.Add(
                new Soap.Behaviors.SoapClientBehavior()
                );

            var channelWithIssuedToken =
                factory.CreateChannelWithIssuedToken(securityToken);

            var helloWorldRequestJohn = new HelloWorldRequest("John");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJohn).response
                );

            var helloWorldRequestJane = new HelloWorldRequest("Jane");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJane).response
                );

            try
            {
                // third call will trigger a SOAPFault
                var helloWorldRequest = new HelloWorldRequest("");
                Console.WriteLine(
                    channelWithIssuedToken.HelloWorld(helloWorldRequest).response
                    );
            }
            catch (Exception ex)
            {
                Console.WriteLine("Expected SOAPFault caught: " + ex.Message);
            }

            // Encrypted calls fails client side. However, encryption at message
            // level is not required and no further investigation has been
            // putted into this issue yet.
            //
            // Console.WriteLine(channelWithIssuedToken.HelloEncryptAndSign("Schultz"));

            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
Example #15
0
        static void Main(string[] args)
        {
            // Setup Log4Net configuration by loading it from configuration file
            // log4net is not necessary and is only being used for demonstration
            XmlConfigurator.Configure();

            // To ensure that the WSP is up and running.
            Thread.Sleep(1000);

            // Retrieve token
            IStsTokenService stsTokenService =
                new StsTokenServiceCache(
                    TokenServiceConfigurationFactory.CreateConfiguration()
                    );
            var securityToken = stsTokenService.GetToken();

            // Call WSP with token
            var hostname        = "https://Digst.OioIdws.Wsp:9090/HelloWorld";
            var customBinding   = new Channels.CustomBinding();
            var endpointAddress = new System.ServiceModel.EndpointAddress(
                new Uri(hostname),
                System.ServiceModel.EndpointIdentity.CreateDnsIdentity(
                    "wsp.oioidws-net.dk TEST (funktionscertifikat)"
                    ),
                new Channels.AddressHeader[] { }
                );

            var asymmetric =
                new Channels.AsymmetricSecurityBindingElement
                (
                    new SecurityTokens.X509SecurityTokenParameters(
                        SecurityTokens.X509KeyIdentifierClauseType.Any,
                        SecurityTokens.SecurityTokenInclusionMode.AlwaysToInitiator
                        ),
                    new Soap.StrCustomization.CustomizedIssuedSecurityTokenParameters(
                        "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
                        )
            {
                UseStrTransform = true
            }
                )
            {
                AllowSerializedSigningTokenOnReply = true,
                ProtectTokens = true
            };

            asymmetric.SetKeyDerivation(false);
            var messageEncoding =
                new Channels.TextMessageEncodingBindingElement
            {
                MessageVersion =
                    Channels.MessageVersion.Soap12WSAddressing10
            };
            var transport =
                (hostname.ToLower().StartsWith("https://"))
                    ? new Channels.HttpsTransportBindingElement()
                    : new Channels.HttpTransportBindingElement();

            customBinding.Elements.Add(asymmetric);
            customBinding.Elements.Add(messageEncoding);
            customBinding.Elements.Add(transport);

            System.ServiceModel.ChannelFactory <IHelloWorld> factory =
                new System.ServiceModel.ChannelFactory <IHelloWorld>(
                    customBinding, endpointAddress
                    );
            factory.Credentials.UseIdentityConfiguration = true;
            factory.Credentials.ServiceCertificate.SetScopedCertificate(
                X509Certificates.StoreLocation.LocalMachine,
                X509Certificates.StoreName.My,
                X509Certificates.X509FindType.FindByThumbprint,
                "1F0830937C74B0567D6B05C07B6155059D9B10C7",
                new Uri(hostname)
                );
            factory.Endpoint.Behaviors.Add(
                new Soap.Behaviors.SoapClientBehavior()
                );

            var channelWithIssuedToken =
                factory.CreateChannelWithIssuedToken(securityToken);

            Console.WriteLine(channelWithIssuedToken.HelloNone("Schultz"));
            Console.WriteLine(channelWithIssuedToken.HelloSign("Schultz"));
            Console.WriteLine(channelWithIssuedToken.HelloEncryptAndSign("Schultz"));

            // Checking that SOAP faults can be read. SOAP faults are encrypted
            // in Sign and EncryptAndSign mode if no special care is taken.
            try
            {
                channelWithIssuedToken.HelloSignError("Schultz");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            // Checking that SOAP faults can be read when only being signed.
            // SOAP faults are only signed if special care is taken.
            try
            {
                channelWithIssuedToken.HelloSignErrorNotEncrypted("Schultz");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }