Beispiel #1
0
        static void Main(string[] args)
        {
            CalculatorClient client1 = new CalculatorClient("calculatorservice");

            client1.Open();
            CalculatorClient client2 = new CalculatorClient("calculatorservice");

            client2.Open();

            client1.Close();
            client2.Close();

            Console.WriteLine("ChannelFactory的状态: {0}", client1.ChannelFactory.State);
            Console.WriteLine("ChannelFactory的状态: {0}\n", client2.ChannelFactory.State);

            EndpointAddress address = new EndpointAddress("http://127.0.0.1:3721/calculatorservice");
            Binding         binding = new WS2007HttpBinding();

            CalculatorClient client3 = new CalculatorClient(binding, address);

            client3.Open();
            CalculatorClient client4 = new CalculatorClient(binding, address);

            client4.Open();

            client3.Close();
            client4.Close();

            Console.WriteLine("ChannelFactory的状态: {0}", client3.ChannelFactory.State);
            Console.WriteLine("ChannelFactory的状态: {0}", client4.ChannelFactory.State);

            Console.Read();
        }
Beispiel #2
0
        public void BusinessToBusinessCert_BasicHttp()
        {
            string uri = "http://localhost/servicehelpers";

            using (var host = new ServiceHost(typeof(BusinessToBusiness1), new Uri(uri)))
            {
                host.AddServiceEndpoint(typeof(IBusinessToBusiness1), new BasicHttpBinding(), uri);
                host.Open();


                // raw proxy
                var clientBinding = new WS2007HttpBinding(SecurityMode.Message);
                clientBinding.Security.Message.ClientCredentialType     = MessageCredentialType.Certificate;
                clientBinding.Security.Message.EstablishSecurityContext = false;

                EndpointIdentity identity = new DnsEndpointIdentity("RawTcpServiceCert1");

                var factory = new ChannelFactory <IBusinessToBusiness1>(clientBinding, new EndpointAddress(new Uri(uri), identity));
                factory.Credentials.ClientCertificate.SetCertificate(
                    "CN=RawTcpClientCert1",
                    System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                    System.Security.Cryptography.X509Certificates.StoreName.My);
                factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;

                var channel = factory.CreateChannel();
                Assert.AreEqual("hi", channel.TestMe("hi"));

                factory.Close();
            }
        }
Beispiel #3
0
        public IInstanceTestService GetService(string username, string password)
        {
            if (_singleton == null)
            {
                var url     = new Uri(TestingServer.BaseAddress, "singleton");
                var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
                binding.Security.Message.ClientCredentialType     = MessageCredentialType.UserName;
                binding.Security.Message.EstablishSecurityContext = false;
                var endpoint = new EndpointAddress(url);
                var factory  = new ChannelFactory <IInstanceTestService>(binding, endpoint);

                factory.Credentials.UserName.UserName = username;
                factory.Credentials.UserName.Password = password;

                var client = factory.CreateChannel();
                _singleton = client;

                var channel = client as ICommunicationObject;
                channel.Closed += (sender, args) =>
                {
                    _singleton = null;
                };
            }
            return(_singleton);
        }
Beispiel #4
0
        /// <summary>
        /// Create the communication channel to the SIMS security server.
        /// Instead of relying on unweildy .config files full of WCF binding information, we will do this longhand as an example.
        /// </summary>
        /// <returns>A channel factory configured with WS2007HttpBinding</returns>
        private WSTrustChannelFactory GetTrustChannelFactory()
        {
            // Use WS2007HttpBinding
            WS2007HttpBinding binding = new WS2007HttpBinding();

            // Timeout settings etc
            binding.CloseTimeout = new TimeSpan(0, 10, 0);
            binding.OpenTimeout  = new TimeSpan(0, 10, 0);
            binding.SendTimeout  = new TimeSpan(0, 10, 0);
            // Quotas
            binding.ReaderQuotas.MaxArrayLength         = 2147483647;
            binding.ReaderQuotas.MaxStringContentLength = 2147483647;
            binding.ReaderQuotas.MaxDepth  = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;

            // SSL security mode
            binding.Security.Mode = SecurityMode.TransportWithMessageCredential;

            // The credentials we will pass will be username/password
            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.EstablishSecurityContext   = false;
            binding.Security.Message.NegotiateServiceCredential = true;

            binding.UseDefaultWebProxy = true;
            binding.BypassProxyOnLocal = false;

            EndpointAddress endpointAddress = new EndpointAddress(new Uri(_securityServerAddress));

            WSTrustChannelFactory channelFactory = new WSTrustChannelFactory(binding, endpointAddress);

            return(channelFactory);
        }
        ManualResetEvent m_deviceSelected; // Tells the app a device is selected

        public TestApplication()
        {
            m_threadLock     = new object();
            m_inOperation    = false;
            m_deviceSelected = new ManualResetEvent(false);

            m_version = new ProtocolVersion11();
            // To enable WSDiscoveryApril2005 and Soap12WSAddressingAugust2004
            //m_version = new ProtocolVersion10();
            m_eventSubscriptionAddress = "";
            m_deviceEndpointAddress    = "";

            m_simpleServiceClient = new SimpleServiceClientProxy(new WS2007HttpBinding(), m_version);

            // Event handling requires that we have a defined port (other than 8084)
            WS2007HttpBinding binding = new WS2007HttpBinding(new HttpTransportBindingConfig("urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b07", 15338, true));

            m_eventingServiceClient = new EventingServiceClientProxy(binding, m_version, new EventingClientImplementation());

            m_attachmentServiceClient = new AttachmentServiceClientProxy(new WS2007HttpBinding(), m_version);

            // Turn listening to this IP on
            m_simpleServiceClient.IgnoreRequestFromThisIP     = false;
            m_eventingServiceClient.IgnoreRequestFromThisIP   = false;
            m_attachmentServiceClient.IgnoreRequestFromThisIP = false;

            m_discoClient = new DiscoClient(m_simpleServiceClient);

            m_random = new Random();
        }
Beispiel #6
0
        public void Raw_HttpCert_Config()
        {
            string uri = "http://localhost/servicehelpers";

            using (var host = new ServiceHost(typeof(RawTcpCertServiceConfig), new Uri(uri)))
            {
                var serviceBinding = new WS2007HttpBinding(SecurityMode.Message);
                serviceBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
                host.Credentials.ServiceCertificate.SetCertificate(
                    "CN=RawTcpServiceCert1",
                    System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                    System.Security.Cryptography.X509Certificates.StoreName.My);
                host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;

                host.AddServiceEndpoint(typeof(IRawTcpCertServiceConfig), serviceBinding, uri);

                host.Open();

                var factory = new ChannelFactory <IRawTcpCertServiceConfig>("IRawTcpCertServiceConfig");

                var channel = factory.CreateChannel();
                Assert.AreEqual("hi", channel.TestMe("hi"));

                factory.Close();
            }
        }
        public void ConfigureService(System.ServiceModel.Description.ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            var host = (serviceHostBase as ServiceHost);

            if (host != null)
            {
                // Don't use this crappy binding
                var address  = serviceHostBase.Description.Endpoints.First().Address;
                var contract = serviceHostBase.Description.Endpoints.First().Contract;

                // clear existing
                host.Description.Endpoints.Clear();

                var binding = new WS2007HttpBinding();
                binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
                binding.Security.Message.ClientCredentialType     = MessageCredentialType.Certificate;
                binding.Security.Message.EstablishSecurityContext = false;
                binding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.Certificate;

                MaxSetter.SetMaxes(binding);

                if (address.Uri.ToString().Contains("http://"))
                {
                    address = new EndpointAddress(new Uri(address.Uri.ToString().Replace("http://", "https://")));
                }
                var endpoint = host.AddServiceEndpoint(contract.ContractType, binding, address.Uri);

                host.Description.Behaviors.Add(new ServiceMetadataBehavior()
                {
                    HttpGetEnabled = true, HttpsGetEnabled = true
                });
            }

            DisableErrorMasking.Disable(serviceHostBase);
        }
        private WSTrustChannel CreateWSTrustChannel(string username, string password)
        {
            var binding = new WS2007HttpBinding(SecurityMode.Message);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var timeSpan = new TimeSpan(0, 5, 0);

            binding.SendTimeout    = timeSpan;
            binding.ReceiveTimeout = timeSpan;
            binding.OpenTimeout    = timeSpan;
            binding.CloseTimeout   = timeSpan;

            EndpointIdentity identity = EndpointIdentity.CreateDnsIdentity(_tokenClientOptions.CertificateDnsIdentity);
            var address = new EndpointAddress(_tokenClientOptions.TokenServiceUri, identity);

            var factory = new WSTrustChannelFactory(binding, address);

            if (factory.Credentials == null)
            {
                throw new NullReferenceException(nameof(WSTrustChannelFactory.Credentials));
            }

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;
            factory.Credentials.ServiceCertificate.Authentication.RevocationMode            = X509RevocationMode.NoCheck;
            factory.Credentials.SupportInteractive = false;
            factory.Credentials.UserName.UserName  = username;
            factory.Credentials.UserName.Password  = password;

            return((WSTrustChannel)factory.CreateChannel());
        }
Beispiel #9
0
        private static ConnectorIncidentManagerClient CreateConnectorClient(string icmWebServiceBaseUrl)
        {
            WS2007HttpBinding binding = new WS2007HttpBinding(SecurityMode.Transport)
            {
                Name = "IcmBindingConfigCert",
                MaxBufferPoolSize      = 4194304,
                MaxReceivedMessageSize = 16777216
            };

            binding.Security.Transport.Realm = string.Empty;
            binding.Security.Transport.ProxyCredentialType      = HttpProxyCredentialType.None;
            binding.Security.Transport.ClientCredentialType     = HttpClientCredentialType.Certificate;
            binding.Security.Message.EstablishSecurityContext   = false;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.AlgorithmSuite             = SecurityAlgorithmSuite.Default;
            binding.Security.Message.ClientCredentialType       = MessageCredentialType.Certificate;

            EndpointAddress remoteAddress = new EndpointAddress(icmWebServiceBaseUrl);

            ConnectorIncidentManagerClient client = new ConnectorIncidentManagerClient(binding, remoteAddress);

            if (client.ClientCredentials != null)
            {
                client.ClientCredentials.ClientCertificate.SetCertificate(
                    StoreLocation.LocalMachine,
                    StoreName.My,
                    X509FindType.FindByThumbprint,
                    CertThumbprint);
            }

            return(client);
        }
        public void ConfigureService(System.ServiceModel.Description.ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            var host = (serviceHostBase as ServiceHost);

            if (host != null)
            {
                var address  = serviceHostBase.Description.Endpoints.First().Address;
                var contract = serviceHostBase.Description.Endpoints.First().Contract;

                if (address.ToString().ToLower().Contains("http"))
                {
                    // clear existing
                    host.Description.Endpoints.Clear();

                    // Use HTTPS (SSL) for communication
                    var binding = new WS2007HttpBinding(SecurityMode.Transport);
                    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

                    MaxSetter.SetMaxes(binding);

                    if (address.Uri.ToString().Contains("http://"))
                    {
                        var uri = address.Uri.ToString().Replace("http://", "https://");
                        if (ServiceHelpersConfigSection.Settings != null && ServiceHelpersConfigSection.Settings.SSLPort > 0)
                        {
                            uri = uri.Replace(address.Uri.Port.ToString(), ServiceHelpersConfigSection.Settings.SSLPort.ToString());
                        }
                        address = new EndpointAddress(new Uri(uri));
                    }
                    var endpoint = host.AddServiceEndpoint(contract.ContractType, binding, address.Uri);
                }
            }
            DisableErrorMasking.Disable(serviceHostBase);
        }
Beispiel #11
0
        private static string GetSTSToken(Uri requestUri, string endPoint, string appliesTo)
        {
            var typeProvider = WIFTypeProvider.GetWIFTypes();

            if (typeProvider == null)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToLocateWIF, requestUri));
            }

            var     binding = new WS2007HttpBinding(SecurityMode.Transport);
            dynamic factory = Activator.CreateInstance(typeProvider.ChannelFactory, binding, endPoint);

            factory.TrustVersion = TrustVersion.WSTrust13;

            // Check if we can create 4.5 types.
            dynamic rst = Activator.CreateInstance(typeProvider.RequestSecurityToken);

            rst.RequestType = GetFieldValue <string>(typeProvider.RequestTypes, "Issue");
            rst.KeyType     = GetFieldValue <string>(typeProvider.KeyTypes, "Bearer");

            // Dynamic verifies the type of the instance so we cannot use it to assign a value for this property.
            var endPointAddress = Activator.CreateInstance(typeProvider.EndPoint, appliesTo);

            SetProperty(rst, "AppliesTo", endPointAddress);

            dynamic channel       = factory.CreateChannel();
            dynamic securityToken = channel.Issue(rst);

            return(securityToken.TokenXml.OuterXml);
        }
Beispiel #12
0
        private Binding CreateBinding()
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.EstablishSecurityContext = false;
            return(binding);
        }
         public static SecurityToken GetToken(string username, string password, string tokenIssuer, string appliesTo, out RequestSecurityTokenResponse rsts)
 
         {
             WS2007HttpBinding binding = new WS2007HttpBinding();
             binding.Security.Message.EstablishSecurityContext = false;
             binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
             binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
             binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
 
 
             var tokenIssuerUrlFormat = "https://{0}/adfs/services/trust/13/usernamemixed";
             var tokenIssuerUrl = string.Format(tokenIssuerUrlFormat, tokenIssuer);
 
 
             WSTrustChannelFactory trustChannelFactory =
                 new WSTrustChannelFactory(binding, new EndpointAddress(tokenIssuerUrl));
 
             trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
             trustChannelFactory.Credentials.UserName.UserName = username;
             trustChannelFactory.Credentials.UserName.Password = password;
 
             trustChannelFactory.ConfigureChannelFactory();
 
 
 
             // Create issuance issuance and get security token 
             RequestSecurityToken requestToken = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
             requestToken.AppliesTo = new EndpointAddress(appliesTo);
 
             WSTrustChannel tokenClient = (WSTrustChannel) trustChannelFactory.CreateChannel();
             SecurityToken token = tokenClient.Issue(requestToken, out rsts);
             return token;
 
         }
Beispiel #14
0
        private static Tuple <string, byte[]> GetToken()
        {
            var binding = new WS2007HttpBinding(SecurityMode.Message);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var address = new EndpointAddress(new Uri(@"http://localhost:6000/MySTS"),
                                              new DnsEndpointIdentity("MySTS"));

            WSTrustChannelFactory factory = new WSTrustChannelFactory(binding, address);

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode =
                X509CertificateValidationMode.None;
            factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******"; // got to be same as user name in our example

            WSTrustChannel channel = (WSTrustChannel)factory.CreateChannel();

            var request = new RequestSecurityToken(System.IdentityModel.Protocols.WSTrust.RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://my-server.com")
            };

            RequestSecurityTokenResponse response = null;
            var token = channel.Issue(request, out response) as GenericXmlSecurityToken;

            var proofKey = response.RequestedProofToken.ProtectedKey.GetKeyBytes();

            return(new Tuple <string, byte[]>(token.TokenXml.OuterXml, proofKey));
        }
Beispiel #15
0
        private static string GetTokenFromAdfs20()
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var address = new EndpointAddress(
                new Uri(@"https://yourserver.com/adfs/services/trust/13/usernamemixed"));

            WSTrustChannelFactory factory = new WSTrustChannelFactory(binding, address);

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";

            WSTrustChannel channel = (WSTrustChannel)factory.CreateChannel();

            var request = new RequestSecurityToken(System.IdentityModel.Protocols.WSTrust.RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("https://relyingparty"),
                KeyType   = KeyTypes.Bearer
            };

            RequestSecurityTokenResponse response = null;
            var token = channel.Issue(request, out response) as GenericXmlSecurityToken;

            return(token.TokenXml.OuterXml);
        }
Beispiel #16
0
        static void UseAddressHeader()
        {
            using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
            {
                AddressHeader   header  = AddressHeader.CreateAddressHeader("UserType", "http://www.aaa.com", "Licensed User");
                EndpointAddress address = new EndpointAddress(new Uri("http://127.0.0.1:23232/myservices/calculatorservice"), header);
                //EndpointAddress address = new EndpointAddress(new Uri("http://127.0.0.1:23232/myservices/calculatorservice"));

                Binding             httpBinding = new WS2007HttpBinding();
                ContractDescription contract    = ContractDescription.GetContract(typeof(ICalculator));
                ServiceEndpoint     endPoint    = new ServiceEndpoint(contract, httpBinding, address);

                serviceHost.AddServiceEndpoint(endPoint);

                if (serviceHost.Description.Behaviors.Find <ServiceMetadataBehavior>() == null)
                {
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl     = new Uri("http://127.0.0.1:23232/myservices/calculatorservice/metadata");
                    serviceHost.Description.Behaviors.Add(behavior);
                }

                serviceHost.Opened += delegate
                {
                    Console.WriteLine("CalculatorService is opened, press any key to end service.");
                };
                serviceHost.Open();

                Console.Read();
            }
        }
        private static string GetWindowsTokenHelper(string windowsAuthSiteEndPoint)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/wstrust/issue/windowstransport"));
            var identityProviderBinding  = new WS2007HttpBinding(SecurityMode.Transport);

            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType     = MessageCredentialType.None;
            identityProviderBinding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.Windows;

            var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13,
            };

            trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
            {
                CertificateValidationMode = X509CertificateValidationMode.None
            };
            var channel = trustChannelFactory.CreateChannel();

            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://azureservices/AdminSite"),
                KeyType   = KeyTypes.Bearer,
            };

            RequestSecurityTokenResponse rstr = null;
            SecurityToken token = null;

            token = channel.Issue(rst, out rstr);
            var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
            var jwtString   = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

            return(jwtString);
        }
        ManualResetEvent m_deviceSelected; // Tells the app a device is selected

        public TestApplication()
        {
            m_threadLock     = new object();
            m_inOperation    = false;
            m_deviceSelected = new ManualResetEvent(false);

            ProtocolVersion version = new ProtocolVersion10();

            WS2007HttpBinding binding = new WS2007HttpBinding(new HttpTransportBindingConfig("urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b06", 15337));

            m_simpleServiceClient = new SimpleServiceClientProxy(binding, new ProtocolVersion10());

            binding = new WS2007HttpBinding(new HttpTransportBindingConfig("urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b07", 15338));
            m_eventingServiceClient = new EventingServiceClientProxy(binding, version, new EventingClientImplementation());

            binding = new WS2007HttpBinding(new HttpTransportBindingConfig("urn:uuid:3cb0d1ba-cc3a-46ce-b416-212ac2419b08", 15339));
            m_attachmentServiceClient = new AttachmentServiceClientProxy(binding, version);

            // Turn listening to this IP on
            m_simpleServiceClient.IgnoreRequestFromThisIP     = false;
            m_eventingServiceClient.IgnoreRequestFromThisIP   = false;
            m_attachmentServiceClient.IgnoreRequestFromThisIP = false;

            m_discoClient = new DiscoClient(m_simpleServiceClient);

            m_random = new Random();
        }
Beispiel #19
0
        /**
         * This method binding the service
         */
        private Boolean bindProxyService()
        {
            Debug.Print("Binding proxy service...");
            try
            {
                WS2007HttpBinding a = new WS2007HttpBinding();
                ProtocolVersion11 b = new ProtocolVersion11();
                proxy = new IService1ClientProxy(a, b);

                // NOTE: the endpoint needs to match the endpoint of the servicehost
                proxy.EndpointAddress = SERVICE_ADDR;
            }
            catch (SocketException e)
            {
                WindowsManager.showWindowServiceDown();
                return(false);
            }
            catch (ObjectDisposedException e)
            {
                Debug.Print("Disposed object exception");
                WindowsManager.showWindowServiceDown();
                return(false);
            }


            Debug.Print("Binding proxy service COMPLETE");
            return(true);
        }
Beispiel #20
0
        private WSTrustChannelFactory GetTrustChannelFactory(string securityServerURL)
        {
            WS2007HttpBinding binding = new WS2007HttpBinding
            {
                CloseTimeout = new TimeSpan(0, 10, 0),
                OpenTimeout  = new TimeSpan(0, 10, 0),
                SendTimeout  = new TimeSpan(0, 10, 0),
                ReaderQuotas =
                {
                    MaxArrayLength         = 2147483647,
                    MaxStringContentLength = 2147483647,
                    MaxDepth               = int.MaxValue
                },
                MaxReceivedMessageSize = int.MaxValue,
                Security =
                {
                    Mode    = SecurityMode.TransportWithMessageCredential,
                    Message =
                    {
                        ClientCredentialType       = MessageCredentialType.UserName,
                        EstablishSecurityContext   = false,
                        NegotiateServiceCredential = true
                    }
                },
                UseDefaultWebProxy = true,
                BypassProxyOnLocal = false
            };

            EndpointAddress endpointAddress = new EndpointAddress(new Uri(securityServerURL));

            WSTrustChannelFactory channelFactory = new WSTrustChannelFactory(binding, endpointAddress);

            return(channelFactory);
        }
Beispiel #21
0
        public static WS2007HttpBinding GetStsBinding()
        {
            var stsBinding = new WS2007HttpBinding(SecurityMode.Message);

            stsBinding.Security.Message.EstablishSecurityContext = false;

            return(stsBinding);
        }
        private Binding GetHttpsBinding()
        {
            var binding = new WS2007HttpBinding(SecurityMode.Transport);

            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;

            return(binding);
        }
        private Binding GetWS2007HttpBinding()
        {
            WS2007HttpBinding binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
            binding.Name = "https2007-message-credentials-cert";
            return(binding);
        }
        public static Binding CreateBinding(string bindingName)
        {
            Binding result = null;

            try
            {
                if (string.Compare(bindingName, typeof(WSHttpBinding).FullName, true) == 0)
                {
                    result = new WSHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WS2007HttpBinding).FullName, true) == 0)
                {
                    result = new WS2007HttpBinding();
                }
                else if (string.Compare(bindingName, typeof(BasicHttpBinding).FullName, true) == 0)
                {
                    result = new BasicHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WSDualHttpBinding).FullName, true) == 0)
                {
                    result = new WSDualHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WS2007FederationHttpBinding).FullName, true) == 0)
                {
                    result = new WS2007FederationHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(WSFederationHttpBinding).FullName, true) == 0)
                {
                    result = new WSFederationHttpBinding();
                }
                else if (string.Compare(bindingName, typeof(NetNamedPipeBinding).FullName, true) == 0)
                {
                    result = new NetNamedPipeBinding();
                }
                else if (string.Compare(bindingName, typeof(NetMsmqBinding).FullName, true) == 0)
                {
                    result = new NetMsmqBinding();
                }
                else if (string.Compare(bindingName, typeof(MsmqIntegrationBinding).FullName, true) == 0)
                {
                    result = new MsmqIntegrationBinding();
                }
                else if (string.Compare(bindingName, typeof(NetTcpBinding).FullName, true) == 0)
                {
                    result = new NetTcpBinding();
                }
                else if (string.Compare(bindingName, typeof(NetPeerTcpBinding).FullName, true) == 0)
                {
                    result = new NetPeerTcpBinding();
                }
            }
            catch
            {
                result = new BasicHttpBinding(BasicHttpSecurityMode.None);
            }

            return(result);
        }
        private static string GetADFSMembershipTokenHelper(string adfsEndpoint, string authSiteEndPoint, string userName, string password)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed"));
            var federationEndpoint       = new EndpointAddress(new Uri(adfsEndpoint + "/adfs/services/trust/13/issuedtokenmixedasymmetricbasic256sha256"));

            var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType     = MessageCredentialType.UserName;
            identityProviderBinding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.None;

            var xml = new XmlDocument();

            xml.LoadXml(@"<wsp:AppliesTo xmlns:wsp=""http://schemas.xmlsoap.org/ws/2004/09/policy""><wsa:EndpointReference xmlns:wsa=""http://www.w3.org/2005/08/addressing""><wsa:Address>http://kc-adfs.katalcloud.com/adfs/services/trust</wsa:Address></wsa:EndpointReference></wsp:AppliesTo>");
            var federationBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);

            federationBinding.Security.Message.EstablishSecurityContext   = false;
            federationBinding.Security.Message.IssuedKeyType              = SecurityKeyType.AsymmetricKey;
            federationBinding.Security.Message.AlgorithmSuite             = SecurityAlgorithmSuite.Basic256Sha256;
            federationBinding.Security.Message.NegotiateServiceCredential = false;
            federationBinding.Security.Message.TokenRequestParameters.Add(xml.DocumentElement);
            federationBinding.Security.Message.IssuerAddress   = identityProviderEndpoint;
            federationBinding.Security.Message.IssuerBinding   = identityProviderBinding;
            federationBinding.Security.Message.IssuedTokenType = "urn:oasis:names:tc:SAML:2.0:assertion";

            var trustChannelFactory = new WSTrustChannelFactory(federationBinding, federationEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13,
            };

            trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
            {
                CertificateValidationMode = X509CertificateValidationMode.None
            };
            trustChannelFactory.Credentials.SupportInteractive = false;
            trustChannelFactory.Credentials.UserName.UserName  = userName;
            trustChannelFactory.Credentials.UserName.Password  = password;

            var channel = trustChannelFactory.CreateChannel();
            var rst     = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
                TokenType = "urn:ietf:params:oauth:token-type:jwt",
                KeyType   = KeyTypes.Bearer,
            };

            RequestSecurityTokenResponse rstr = null;

            var token       = channel.Issue(rst, out rstr);
            var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
            var jwtString   = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

            return(jwtString);
        }
        static void Main(string[] args)
        {
            EndpointAddress   address = new EndpointAddress(new Uri("http://localhost:47718/Service1.svc"));
            WS2007HttpBinding binding = new WS2007HttpBinding();
            Uri via = new Uri("http://localhost:47718/Service1.svc/via");
            ChannelFactory <ChannelFactoryService.IService1Channel> channelFactory = new ChannelFactory <ChannelFactoryService.IService1Channel>(binding);

            ChannelFactoryService.IService1Channel channel = channelFactory.CreateChannel(address);
            channel.Open();
            Console.WriteLine(channel.GetData(123));
            Console.ReadLine();
        }
        public void CreateChannel_WhenCalled_ReturnsChannel()
        {
            // Arrange
            var securityTokenProvider = new SecurityTokenProvider();
            var issuerBinding         = new WS2007HttpBinding();
            var issuerEndpointAddress = new EndpointAddress("http://localhost/issuer");

            // Act
            var actual = securityTokenProvider.CreateChannel(issuerBinding, issuerEndpointAddress);

            // Assert
            Assert.IsNotNull(actual);
        }
Beispiel #28
0
        public static ClientContext GetSPContext(string webUrl)
        {
            TokenConstants.fedAuthRequestCtx = HttpUtility.UrlEncode(string.Format("{0}/_layouts/15/Authenticate.aspx?Source=%2f", webUrl));
            EndpointAddress   ep      = new EndpointAddress(TokenConstants.adfsBaseUri + "/" + TokenConstants.adfsTrustPath + "/" + TokenConstants.adfsTrustEndpoint);
            WS2007HttpBinding binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.ClientCredentialType     = MessageCredentialType.UserName;
            binding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.None;

            WSTrustChannelFactory wstcf = new WSTrustChannelFactory(binding, ep);

            wstcf.TrustVersion = TrustVersion.WSTrust13;
            NetworkCredential cred = new NetworkCredential(TokenConstants.userName, TokenConstants.pwd, TokenConstants.domain);

            wstcf.Credentials.Windows.ClientCredential = cred;
            wstcf.Credentials.UserName.UserName        = cred.UserName;
            wstcf.Credentials.UserName.Password        = cred.Password;
            var channel = wstcf.CreateChannel();

            string[]             tokenType = { "urn:oasis:names:tc:SAML:1.0:assertion", "urn:oasis:names:tc:SAML:2.0:assertion" };
            RequestSecurityToken rst       = new RequestSecurityToken();

            rst.RequestType = RequestTypes.Issue;
            rst.AppliesTo   = new EndpointReference(TokenConstants.adfsRealm);
            rst.KeyType     = KeyTypes.Bearer;
            rst.TokenType   = tokenType[0]; // Use the first one because that is what SharePoint itself uses (as observed in Fiddler).

            RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse();
            var cbk = new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);

            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); };
            SecurityToken token = null;

            try
            {
                token = channel.Issue(rst, out rstr);
            }
            finally
            {
                ServicePointManager.ServerCertificateValidationCallback = cbk;
            }

            Cookie fedAuthCookie = TransformTokenToFedAuth(((GenericXmlSecurityToken)token).TokenXml.OuterXml);

            TokenConstants.fedAuth.Add(fedAuthCookie);
            SP.ClientContext ctx = new SP.ClientContext(webUrl);
            ctx.ExecutingWebRequest += ctx_ExecutingWebRequest;
            return(ctx);
        }
        private Binding CreateBinding(MessageCredentialType credentialType, SoapChannelCreationContext context)
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.ClientCredentialType     = credentialType;

            if (context.Properties.TryGetValue("securityAlgorithmSuite", out var value) && value is SecurityAlgorithmSuite securityAlgorithmSuite)
            {
                binding.Security.Message.AlgorithmSuite = securityAlgorithmSuite;
            }

            return(binding);
        }
Beispiel #30
0
        private void button2_Click(object sender, EventArgs e)
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            // If you set this to true, you can use a Security Context Token (SCT) for your next
            // calls to the STS instead of sending a Username and Password each time.
            binding.Security.Message.EstablishSecurityContext = false;

            // Instead of using Username/Password authentication you can use any of the
            // other ClientCredentialType's such as Certificate, IssuedToken or Windows.
            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

            // The same applies to the transport level security. You can secure it in any
            // of the available ways.
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

            var endpoint = new EndpointAddress(endPontTxt.Text);
            var factory  = new WSTrustChannelFactory(binding, endpoint);

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;

            // If your MessageCredentialType differs from UserName, make sure you supply
            // the valid credential here.
            factory.Credentials.UserName.UserName = username_ADFS.Text;
            factory.Credentials.UserName.Password = password_ADFS.Text;

            var rst = new RequestSecurityToken()
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                AppliesTo   = new EndpointReference(relyTxt.Text),
                TokenType   = "urn:oasis:names:tc:SAML:2.0:assertion"
            };

            var channel = (WSTrustChannel)factory.CreateChannel();
            RequestSecurityTokenResponse rstr;

            try
            {
                SecurityToken token = channel.Issue(rst, out rstr);
                MessageBox.Show("Success", "Authenticated");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception");
            }
        }