public void TestGenevaWebserviceProvider_WithSSL()
        {
            X509Certificate2 sslCertJavaWSP = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, JavaWSPSSLCertificate);

            X509Certificate2 certificate2Client = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateNameClient);

            //            Uri uri = new Uri("http://localhost:6020/Echo");
            Uri             uri     = new Uri("https://csky-pc/test/Service1.svc");
            EndpointAddress address = new EndpointAddress(uri);

            SecurityToken issuedToken = TestJavaSTSConnection.GetIssuedToken();

            using (ChannelFactory <IEchoService> factory = new ChannelFactory <IEchoService>(new ServiceproviderBinding(true), address))
            {
                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
                factory.ConfigureChannelFactory();
                factory.Credentials.ClientCertificate.Certificate         = certificate2Client;
                factory.Credentials.ServiceCertificate.DefaultCertificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=STS");// SigningCertificateNameGenevaService);
                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;

                var service = ChannelFactoryOperations.CreateChannelWithIssuedToken <IEchoService>(factory, issuedToken);

                Structure str = new Structure();
                str.value = "Badabam";
                var echoRequest = new echo();
                echoRequest.Framework       = new LibertyFrameworkHeader();
                echoRequest.structureToEcho = str;

                var result = service.Echo(echoRequest);
                Assert.AreEqual("Badabam", result.structureToEcho.value);
            }
        }
        public void WrongProfileForLibertyHeader()
        {
            X509Certificate2 certificate2Client = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateNameClient);

            Uri uri = new Uri("http://csky-pc/test/Service1.svc");

            EndpointAddress address = new EndpointAddress(uri);

            SecurityToken issuedToken = TestJavaSTSConnection.GetIssuedToken();

            using (ChannelFactory <IEchoService> factory = new ChannelFactory <IEchoService>(new ServiceproviderBinding(false), address))
            {
                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
                factory.ConfigureChannelFactory();
                factory.Credentials.ClientCertificate.Certificate         = certificate2Client;
                factory.Credentials.ServiceCertificate.DefaultCertificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateNameGenevaService);

                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;

                var service = ChannelFactoryOperations.CreateChannelWithIssuedToken <IEchoService>(factory, issuedToken);

                Structure str = new Structure();
                str.value = "Badabam";
                var echoRequest = new echo();
                echoRequest.Framework         = new LibertyFrameworkHeader();
                echoRequest.Framework.Profile = "FailurToComply";
                echoRequest.structureToEcho   = str;

                var result = service.Echo(echoRequest);
            }
        }
Beispiel #3
0
        void FederatedAuthentication_ServiceConfigurationCreated(object sender, EventArgs e)
        {
            ChannelFactory <IService2Channel> service2CF = new ChannelFactory <IService2Channel>("CustomBinding_IService2");

            service2CF.Credentials.ServiceCertificate.SetDefaultCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My);
            service2CF.ConfigureChannelFactory();

            Application[CachedChannelFactory] = service2CF;
        }
        public static ChannelFactory <T> CreateResourceChannelFactory <T>(string endpointName, Action <ChannelFactory <T>, ClientCredentials> ac)
        {
            var resourceFactory = new ChannelFactory <T>(endpointName);

            ConfigBinding(resourceFactory.Endpoint.Binding);
            ac(resourceFactory, resourceFactory.Credentials);
            resourceFactory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
            resourceFactory.ConfigureChannelFactory();
            return(resourceFactory);
        }
        private static void CallMixedMode(SamlSecurityToken token)
        {
            var factory = new ChannelFactory <IServiceClientChannel>("*");

            factory.ConfigureChannelFactory <IServiceClientChannel>();
            var proxy = factory.CreateChannelWithIssuedToken <IServiceClientChannel>(token);

            proxy.Ping("foo");
            proxy.Close();
        }
        /// <summary>
        /// Calls the Calculator service and uses an issued token explicitly rather
        /// than allowing WCF and the Windows Identity Foundation manage the issued token
        /// retrieval process.
        /// </summary>
        /// <param name="token">The security token.</param>
        private static void CallServiceWithExplicitToken(SecurityToken token)
        {
            //
            // Instantiate the ChannelFactory as usual.
            //
            ChannelFactory <ICalculator> calcFactory = new ChannelFactory <ICalculator>(GetClientBinding(), ServiceAddress);

            //
            // Make sure to call this prior to using the CreateChannelWith...()
            // extension methods on the channel factory that the Windows Identity Foundation
            // provides.
            //
            calcFactory.ConfigureChannelFactory();

            ICommunicationObject channel = null;
            bool succeeded = false;

            try
            {
                //
                // Creates a channel that will use the provided issued token to
                // secure the messages sent to the calculator service.
                // Note that the configuration of this channel factory is identical
                // to the "fully automated" scenario except for the use of this
                // extension method to create the actual channel.
                //
                ICalculator calc = calcFactory.CreateChannelWithIssuedToken(token);
                channel = (ICommunicationObject)calc;

                double sum = calc.Add(40.0, 2.0);
                Console.WriteLine("The sum is {0}", sum);

                channel.Close();
                succeeded = true;
            }
            catch (CommunicationException e)
            {
                Console.WriteLine("=== Communication exception caught ===");
                Console.WriteLine(e.ToString());
                channel.Abort();
            }
            catch (TimeoutException)
            {
                Console.WriteLine("Timed out...");
                channel.Abort();
            }
            finally
            {
                if (!succeeded)
                {
                    channel.Abort();
                }
            }
        }
        public static ChannelFactory <TContract> CreateChannelFactory <TContract>(string endpointConfigurationName)
        {
            var channelFactory = new ChannelFactory <TContract>(endpointConfigurationName);

            if (channelFactory.IsFederated())
            {
                channelFactory.ConfigureChannelFactory();
            }

            return(channelFactory);
        }
        public void IsConfiguredAsFederated_ConfiguredIsCalled_ReturnsTrue()
        {
            // Arrange
            var channelFactory = new ChannelFactory <IService>(new BasicHttpBinding(), new EndpointAddress("http://localhost"));

            channelFactory.ConfigureChannelFactory();

            // Act
            var actual = channelFactory.IsConfiguredAsFederated();

            // Assert
            Assert.AreEqual(true, actual);
        }
        public static string ExecuteWS(string signingCertificateNameClient, string address, SecurityToken issuedToken)
        {
            X509Certificate2 certificate2Client   = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateNameClient);
            ChannelFactory <IEchoService> factory = null;

            try
            {
                factory = new ChannelFactory <IEchoService>(new ServiceproviderBinding(false), address);
                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
                factory.ConfigureChannelFactory();
                factory.Credentials.ClientCertificate.Certificate         = certificate2Client;
                factory.Credentials.ServiceCertificate.DefaultCertificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=STS");// SigningCertificateNameGenevaService);
                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;

                var service = ChannelFactoryOperations.CreateChannelWithIssuedToken <IEchoService>(factory, issuedToken);

                Structure str = new Structure();
                str.value = "Testing .NET client";
                var echoRequest = new echo();
                echoRequest.Framework       = new LibertyFrameworkHeader();
                echoRequest.structureToEcho = str;

                echoResponse result = null;
                result = service.Echo(echoRequest);

                return(result.structureToEcho.value);
            }

            catch (Exception e)
            {
                if (factory != null && factory.State == CommunicationState.Opened)
                {
                    factory.Close();
                }

                throw;
            }
            finally
            {
                if (factory.State == CommunicationState.Opened)
                {
                    factory.Close();
                }
            }
        }
        private static void CallMessage(SamlSecurityToken token)
        {
            var factory = new ChannelFactory <IServiceClientChannel>(
                new ClientSamlHttpBinding(SecurityMode.Message),
                new EndpointAddress(
                    new Uri("http://roadie:9000/Services/ClientSaml/Message"),
                    EndpointIdentity.CreateDnsIdentity("Service")));

            factory.Credentials.ServiceCertificate.SetDefaultCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindBySubjectDistinguishedName,
                "CN=Service");

            factory.ConfigureChannelFactory <IServiceClientChannel>();
            var proxy = factory.CreateChannelWithIssuedToken <IServiceClientChannel>(token);

            proxy.Ping("foo");
            proxy.Close();
        }
Beispiel #11
0
        public void CreateFederatedChannel_WhenCalled_DoesNotThrow()
        {
            // Arrange
            var channelFactory = new ChannelFactory <IFederatedService>(new WS2007FederationHttpBinding(), new EndpointAddress("http://localhost"));

            channelFactory.ConfigureChannelFactory();
            var channelFactoryManager = StubChannelFactoryManager(channelFactory);
            var expected = StubSecurityToken();
            var securityTokenProvider = MockRepository.GenerateStub <SecurityTokenProvider>();

            securityTokenProvider.Stub(
                x =>
                x.IssueToken(Arg <WS2007FederationHttpBinding> .Is.Anything, Arg <string> .Is.Anything, Arg <SecurityToken> .Is.Anything)).Return(expected);
            var clientManager = new TestableClientManager(this.TestCache, channelFactoryManager, securityTokenProvider);

            Thread.CurrentPrincipal = StubPrincipal <IPrincipal>(StubIdentity <IIdentity>("SomeName"));

            // Act
            // Assert
            Assert.DoesNotThrow(() => clientManager.CreateFederatedChannel <IFederatedService>(channelFactory));
        }
Beispiel #12
0
        public void GetSecurityToken_WhenTokenIsCached_ReturnsCachedToken()
        {
            // Arrange
            var channelFactory = new ChannelFactory <IService>(new WS2007FederationHttpBinding(), new EndpointAddress("http://localhost"));

            channelFactory.ConfigureChannelFactory();
            var channelFactoryManager = StubChannelFactoryManager(channelFactory);
            var securityTokenProvider = MockRepository.GenerateStub <SecurityTokenProvider>();
            var securityToken         = StubSecurityToken();

            this.TestCache.Add("SomeName_http://localhost/", securityToken, new DateTimeOffset(DateTime.Now.AddMinutes(1)));
            var clientManager = new TestableClientManager(this.TestCache, channelFactoryManager, securityTokenProvider);

            Thread.CurrentPrincipal = StubPrincipal <IPrincipal>(StubIdentity <IIdentity>("SomeName"));

            // Act
            var actual = clientManager.GetSecurityToken(channelFactory);

            // Assert
            Assert.IsNotNull(actual);
            Assert.AreEqual(securityToken, actual);
        }
        public void TestJavaWebserviceProviderWithSSL()
        {
            X509Certificate2 sslCertJavaWSP = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, JavaWSPSSLCertificate);

            X509Certificate2 certificate2Client = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateNameClient);

            Uri uri = new Uri("https://172.16.232.1:8181/poc-provider/ProviderService");
            EndpointIdentity identity = EndpointIdentity.CreateX509CertificateIdentity(sslCertJavaWSP);

            EndpointAddress address = new EndpointAddress(uri, identity);

            SecurityToken issuedToken = TestJavaSTSConnection.GetIssuedToken(new Uri("https://172.16.232.1:8181/poc-provider/ProviderService"));

            ServicePointManager.ServerCertificateValidationCallback = delegate
            {
                return(true);
            };//Removes Validationcheck of SSL certificate, should not be here for Production.

            using (ChannelFactory <IEchoService> factory = new ChannelFactory <IEchoService>(new ServiceproviderBinding(true), address))
            {
                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
                factory.ConfigureChannelFactory();
                factory.Credentials.ClientCertificate.Certificate         = certificate2Client;
                factory.Credentials.ServiceCertificate.DefaultCertificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateNameJavaService);
                factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;

                var service = ChannelFactoryOperations.CreateChannelWithIssuedToken <IEchoService>(factory, issuedToken);

                Structure str = new Structure();
                str.value = "Badabam";
                var echoRequest = new echo();
                echoRequest.Framework       = new LibertyFrameworkHeader();
                echoRequest.structureToEcho = str;

                var result = service.Echo(echoRequest);
                Assert.AreEqual("Badabam", result.structureToEcho.value);
            }
        }
Beispiel #14
0
        public void CreateChannel_FederationBinding_CallsIssueActAsToken()
        {
            // Arrange
            var channelFactory = new ChannelFactory <IService>(new WS2007FederationHttpBinding(), new EndpointAddress("http://localhost"));

            channelFactory.ConfigureChannelFactory();
            var channelFactoryManager = StubChannelFactoryManager(channelFactory);
            var securityTokenProvider = MockRepository.GenerateMock <SecurityTokenProvider>();
            var expectedToken         = StubSecurityToken();

            securityTokenProvider.Stub(
                x => x.IssueToken(Arg <WS2007FederationHttpBinding> .Is.Anything, Arg <string> .Is.Anything, Arg <SecurityToken> .Is.Anything)).Return(expectedToken);
            var clientManager = new ClientManager(this.TestCache, channelFactoryManager, securityTokenProvider);

            Thread.CurrentPrincipal = StubPrincipal <IPrincipal>(StubIdentity <IIdentity>("SomeName"));


            // Act
            var actual = clientManager.CreateChannel <IService>();

            // Assert
            securityTokenProvider.AssertWasCalled(x => x.IssueToken(Arg <WS2007FederationHttpBinding> .Is.Anything, Arg <string> .Is.Anything, Arg <SecurityToken> .Is.Anything));
        }
Beispiel #15
0
        /// <summary>
        /// Echo service that calls the backend service acting as the client. A SAML token is obtained from the STS
        /// Acting on behalf of the client and then the SAML token is presented to the backend service.
        /// </summary>
        /// <param name="value">The client supplied value in the call to this service.</param>
        /// <returns>A string that the client provided.</returns>
        public string Echo(string value)
        {
            IClaimsIdentity identity = (IClaimsIdentity)((IClaimsPrincipal)Thread.CurrentPrincipal).Identity;

            Console.WriteLine("Caller's name: " + identity.Name);
            foreach (Claim claim in identity.Claims)
            {
                Console.WriteLine("ClaimType  : " + claim.ClaimType);
                Console.WriteLine("ClaimValue : " + claim.Value);
                Console.WriteLine();
            }

            string retval = null;

            lock ( service2CFLock )
            {
                if (service2CF == null)
                {
                    // Create a ChannelFactory to talk to the Service.
                    service2CF = new ChannelFactory <IService2Channel>("CustomBinding_IService2");
                    service2CF.ConfigureChannelFactory();
                }
            }

            // Get the client token. Here we are looking for a SAML token as we know from our bindings that the
            // client should have authenticated using a SAML 1.1 token.
            SecurityToken clientToken = null;

            IClaimsPrincipal claimsPrincipal = Thread.CurrentPrincipal as IClaimsPrincipal;

            if (claimsPrincipal != null)
            {
                foreach (IClaimsIdentity claimsIdentity in claimsPrincipal.Identities)
                {
                    if (claimsIdentity.BootstrapToken is SamlSecurityToken)
                    {
                        clientToken = claimsIdentity.BootstrapToken;
                        break;
                    }
                }
            }

            // We couldn't find the client token. This would mean that either IdentityModel's SecurityTokenHandler
            // was not involved in validating this token or IdentityModelServiceAuthorizationManager was not
            // plugged into the ServiceHost.
            if (clientToken == null)
            {
                throw new InvalidOperationException(
                          "Unable to find client token. Check if your ServiceHost is correctly configured.");
            }

            // Create a channel that uses the Client token as the ActAs token. The Channel will use
            // the configured client token when an ActAs token is requested.
            //
            // Note: A new channel must be created for each call.
            IService2Channel channel = service2CF.CreateChannelActingAs <IService2Channel>(clientToken);

            try
            {
                // Call the backend service.
                retval = channel.ComputeResponse(value);
                channel.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                Exception ex = e.InnerException;
                while (ex != null)
                {
                    Console.WriteLine("===========================");
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                    ex = ex.InnerException;
                }
                channel.Abort();
                retval = "Unable to compute the return value";
            }
            catch (TimeoutException)
            {
                Console.WriteLine("Timed out...");
                channel.Abort();
                retval = "Unable to compute the return value";
            }
            catch (Exception e)
            {
                Console.WriteLine("An unexpected exception occured.");
                Console.WriteLine(e.StackTrace);
                channel.Abort();
                retval = "Unable to compute the return value";
            }

            return(retval);
        }
Beispiel #16
0
        public static eHtalkMessage GetResponseSync(eHtalkMessage msg, X509Certificate2 extInterfaCertificate, string esbEndpoint, string relyingParty, string identityProviderURL, X509Certificate2 userCertificate, string wsaddressingTo, Stopwatch stopw)
        {
#if !CC
            IssuedSecurityTokenProvider provider = new IssuedSecurityTokenProvider();
            provider.SecurityTokenSerializer = new WSSecurityTokenSerializer();
            provider.TargetAddress           = new EndpointAddress(new Uri(relyingParty), new AddressHeader[0]);
            provider.IssuerAddress           = new EndpointAddress(new Uri(identityProviderURL), new AddressHeader[0]);
            provider.SecurityAlgorithmSuite  = SecurityAlgorithmSuite.Basic256;
            provider.MessageSecurityVersion  = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
            ClientCredentials credentials = new ClientCredentials
            {
                ClientCertificate = { Certificate = userCertificate }
            };
            provider.IssuerChannelBehaviors.Add(credentials);

            HttpsTransportBindingElement tbe = new HttpsTransportBindingElement
            {
                AuthenticationScheme     = AuthenticationSchemes.Digest,
                RequireClientCertificate = true,
                KeepAliveEnabled         = false
            };
            CustomBinding stsBinding = new CustomBinding(new BindingElement[] { tbe });
            provider.IssuerBinding = stsBinding;

            provider.Open();
            var token = provider.GetToken(TimeSpan.FromSeconds(30.0)) as GenericXmlSecurityToken;
#endif
#if CC
            var cc    = new EhealthCryptoController();
            var token = cc.GetSamlTokenForHealthProfessional(relyingParty);
#endif
            if (token == null)
            {
                throw new ApplicationException("No AT token received");
            }
            Console.WriteLine(string.Format("Ziskany AT token in {0}", stopw.ElapsedMilliseconds));



            CustomBinding          binding = new CustomBinding();
            SecurityBindingElement sbe     = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(new IssuedSecurityTokenParameters()
            {
                RequireDerivedKeys = true, KeyType = SecurityKeyType.SymmetricKey
            });

            sbe.MessageSecurityVersion =
                MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
            sbe.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
            sbe.IncludeTimestamp     = true;
            //sbe.AllowInsecureTransport = true;
            sbe.SetKeyDerivation(true);
            sbe.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
            binding.Elements.Add(sbe);
            binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, System.Text.Encoding.UTF8));
            binding.Elements.Add(new HttpsTransportBindingElement()
            {
                RequireClientCertificate = true, KeepAliveEnabled = true
            });
            var regEx          = new Regex(@"https?://([^/]+)");
            var dnsIdentity    = regEx.Match(wsaddressingTo).Groups[1].Captures[0].Value;
            var channelFactory = new ChannelFactory <IeHealthSyncService>(binding,
                                                                          new EndpointAddress(
                                                                              new Uri(wsaddressingTo),
                                                                              new DnsEndpointIdentity(dnsIdentity),
                                                                              new AddressHeader[] { }));
            channelFactory.Credentials.SupportInteractive                    = false;
            channelFactory.Credentials.ClientCertificate.Certificate         = userCertificate;
            channelFactory.Credentials.ServiceCertificate.DefaultCertificate = extInterfaCertificate;

            channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode =
                X509CertificateValidationMode.None;
            channelFactory.ConfigureChannelFactory <IeHealthSyncService>();
            channelFactory.Endpoint.Behaviors.Add(new ClientViaBehavior(new Uri(esbEndpoint)));
            var channel = channelFactory.CreateChannelWithIssuedToken(token);
            Console.WriteLine(string.Format("vytvoreny kanal: {0}", stopw.ElapsedMilliseconds));
            var stopw1 = new Stopwatch();

            eHtalkMessage data = null;
            int           wait = 1;
            for (int i = 0; i < 20; i++)
            {
                stopw1.Reset();
                stopw1.Start();
                msg.Header.MessageInfo.MessageID = Guid.NewGuid().ToString("D");
                Debug.WriteLine("Start calling", "MyCustom");
                try
                {
                    data = channel.GetData(msg);
                }
                catch (CommunicationException ex)
                {
                    data = channel.GetData(msg);
                }
                Console.WriteLine(string.Format("po {1} sekundach: {0}", stopw1.ElapsedMilliseconds, wait));
                Thread.Sleep(wait * 1000);
                wait = wait * 2;
            }

            return(data);
        }