private static string GetWindowsToken(string windowsAuthSiteEndPoint, string realm)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + TenantApiUri.WindowsAuthSite));
            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(realm),
                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;
        }
        private Binding GetHttpsBinding()
        {
            var binding = new WS2007HttpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;

            return binding;
        }
Exemple #3
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();
        }
        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 IService CreateProxy()
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
            binding.Security.Message.EstablishSecurityContext = false;

            var factory = new ChannelFactory<IService>(binding, _serviceEndpoint);
            return factory.CreateChannel();
        }
 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();
 }
        private static void CallService()
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            binding.Security.Message.EstablishSecurityContext = false;

            var factory = new ChannelFactory<IClaimsService>(
                binding,
                new EndpointAddress("https://adfs.leastprivilege.vm/claimsapp/service.svc"));

            factory.CreateChannel().GetClaims().ToList().ForEach(c => Console.WriteLine(c.Value));
        }
        // This is effectively just a copy of WSHttpBinding.TryCreate(), only it news up the 2007 version
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);

            binding = null;

            // reverse GetTransport
            HttpTransportSecurity transportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();
            UnifiedSecurityMode   mode;

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

            HttpsTransportBindingElement httpsBinding = transport as HttpsTransportBindingElement;

            if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
            {
                if (httpsBinding.MessageSecurityVersion.SecurityPolicyVersion != s_WS2007MessageSecurityVersion.SecurityPolicyVersion)
                {
                    return(false);
                }
            }

            WSHttpSecurity security;

            if (WS2007HttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                WS2007HttpBinding ws2007HttpBinding = new WS2007HttpBinding(security, isReliableSession);

                bool allowCookies;
                if (!WSHttpBinding.TryGetAllowCookiesFromTransport(transport, out allowCookies))
                {
                    return(false);
                }

                ws2007HttpBinding.AllowCookies = allowCookies;
                binding = ws2007HttpBinding;
            }

            if (rsbe != null && rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11)
            {
                return(false);
            }

            if (tfbe != null && tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11)
            {
                return(false);
            }

            return(binding != null);
        }
        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);
        }
        public static IRequestChannel GetProxy()
        {

            if (_chf == null)
                _chf = new ChannelFactory<ITicketingService>("TicketingEP");

            var binding = new WS2007HttpBinding(); 
            binding.Security.Mode = SecurityMode.None;           
            binding.OpenTimeout = TimeSpan.FromSeconds(600);
            EndpointAddress address = _chf.Endpoint.Address;
            ChannelFactory<IRequestChannel> factory = new ChannelFactory<IRequestChannel>(binding, address);
            return factory.CreateChannel();
        }
 public static Binding Resolve(WcfBindingTypes type)
 {
     Binding binding = null;
     switch (type)
     {
         case WcfBindingTypes.BasicHttpBinding:
             binding = new BasicHttpBinding();
             break;
         case WcfBindingTypes.NetTcpBinding:
             binding = new NetTcpBinding();
             break;
         case WcfBindingTypes.NetTcpContextBinding:
             binding = new NetTcpContextBinding();
             break;
         case WcfBindingTypes.WsHttpBinding:
             binding = new WSHttpBinding();
             break;
         case WcfBindingTypes.NetMsmqBinding:
             binding = new NetMsmqBinding();
             break;
         case WcfBindingTypes.NetPeerTcpBinding:
             binding = new NetPeerTcpBinding();
             break;
         case WcfBindingTypes.BasicHttpContextBinding:
             binding = new BasicHttpContextBinding();
             break;
         case WcfBindingTypes.WSHttpContextBinding:
             binding = new WSHttpContextBinding();
             break;
         case WcfBindingTypes.WS2007FederationHttpBinding:
             binding = new WS2007FederationHttpBinding();
             break;
         case WcfBindingTypes.WS2007HttpBinding:
             binding = new WS2007HttpBinding();
             break;
         case WcfBindingTypes.NetNamedPipeBinding:
             binding = new NetNamedPipeBinding();
             break;
         case WcfBindingTypes.WSFederationHttpBinding:
             binding = new WSFederationHttpBinding();
             break;
         case WcfBindingTypes.WSDualHttpBinding:
             binding = new WSDualHttpBinding();
             break;
         default:
             binding = new CustomBinding();
             break;
     }
     return binding;
 }
        public static string FindCurrentUserOnServer(string password)
        {
            // Accept any old certificate (https)... DO NOT DO THIS IN PRODUCTION
            // Used for self-signed localhost certificate
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => { return true; };

            // ADFS Binding
            var adfsBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            adfsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            var adfsMessage = adfsBinding.Security.Message;
            adfsMessage.ClientCredentialType = MessageCredentialType.UserName;
            adfsMessage.EstablishSecurityContext = false;
            adfsMessage.NegotiateServiceCredential = true;

            // ACS Binding
            var acsBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            var acsMessage = acsBinding.Security.Message;
            acsMessage.IssuedKeyType = SecurityKeyType.BearerKey;
            acsMessage.EstablishSecurityContext = false;
            acsMessage.IssuerAddress = new EndpointAddress("https://sts.planetsoftware.com.au/adfs/services/trust/13/usernamemixed");
            acsMessage.IssuerBinding = adfsBinding;

            // Service Binding
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            var message = binding.Security.Message;
            message.IssuedKeyType = SecurityKeyType.BearerKey;
            message.EstablishSecurityContext = false;
            message.IssuerMetadataAddress = new EndpointAddress("https://soniatest.accesscontrol.windows.net/v2/wstrust/mex");
            message.IssuerAddress = new EndpointAddress("https://soniatest.accesscontrol.windows.net/v2/wstrust/13/issuedtoken-bearer");
            message.IssuerBinding = acsBinding;
            message.ClaimTypeRequirements.Add(new ClaimTypeRequirement("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", true));

            // Create the factory to local service
            var factory = new ChannelFactory<IUserService>(binding, "https://localhost:446/Demo3End/UserService.svc");

            //factory.Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = password;

            var service = factory.CreateChannel();
            var serverUserName = service.GetCurrentUserName();

            factory.Close();

            return serverUserName;
        }
        private static IService CreateProxy()
        {
            // set up factory and channel
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
            binding.Security.Message.EstablishSecurityContext = false;

            // set credentials
            var factory = new ChannelFactory<IService>(binding, _serviceEndpoint);
            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindBySubjectDistinguishedName,
                "CN=Client");

            return factory.CreateChannel();
        }
Exemple #14
0
        private static string GetADFSToken(string windowsAuthSiteEndPoint, string userName, string Password)
        {
            try
            {
                var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/adfs/services/trust/13/usernamemixed"));
                var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
                identityProviderBinding.Security.Message.EstablishSecurityContext = false;
                identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
                identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

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

                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;
                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;
            }
            catch (Exception ex)
            {
                using (EventLog eventLog = new EventLog("Application"))
                {
                    eventLog.Source = "Application";
                    eventLog.WriteEntry("ADFS HealthCheck: " + (object)ex, EventLogEntryType.Error, 1111, (short)1);
                }
                return ex.ToString();
            }
        }
Exemple #15
0
        static void WithHeader() 
        {
            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);

            using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(endPoint))
            {
                ICalculator proxy = channelFactory.CreateChannel();
                Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 1, 2, proxy.Add(1, 2));
                Console.WriteLine("x - y = {2} when x = {0} and y = {1}", 1, 2, proxy.Substract(1, 2));
                Console.WriteLine("x * y = {2} when x = {0} and y = {1}", 1, 2, proxy.Multiply(1, 2));
                Console.WriteLine("x / y = {2} when x = {0} and y = {1}", 1, 2, proxy.Divide(1, 2));
            }
        }
Exemple #16
0
        internal static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            UnifiedSecurityMode mode;
            WSHttpSecurity      security2;
            bool isReliableSession = rsbe != null;

            binding = null;
            HttpTransportSecurity defaultHttpTransportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();

            if (!WSHttpBinding.GetSecurityModeFromTransport(transport, defaultHttpTransportSecurity, out mode))
            {
                return(false);
            }
            HttpsTransportBindingElement element = transport as HttpsTransportBindingElement;

            if (((element != null) && (element.MessageSecurityVersion != null)) && (element.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion))
            {
                return(false);
            }
            if (TryCreateSecurity(sbe, mode, defaultHttpTransportSecurity, isReliableSession, out security2))
            {
                bool flag2;
                WS2007HttpBinding binding2 = new WS2007HttpBinding(security2, isReliableSession);
                if (!WSHttpBinding.TryGetAllowCookiesFromTransport(transport, out flag2))
                {
                    return(false);
                }
                binding2.AllowCookies = flag2;
                binding = binding2;
            }
            if ((rsbe != null) && (rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11))
            {
                return(false);
            }
            if ((tfbe != null) && (tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11))
            {
                return(false);
            }
            return(binding != null);
        }
        public string GetTenantToken(string authSiteEndPoint, string userName, string password, bool validateCertificate, string realm)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + TenantApiUri.AspNetAuthSite));

            var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

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

            if (!validateCertificate)
            {
                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(realm),
                TokenType = "urn:ietf:params:oauth:token-type:jwt",
                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;
        }
 internal static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
 {
     UnifiedSecurityMode mode;
     WSHttpSecurity security2;
     bool isReliableSession = rsbe != null;
     binding = null;
     HttpTransportSecurity defaultHttpTransportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();
     if (!WSHttpBinding.GetSecurityModeFromTransport(transport, defaultHttpTransportSecurity, out mode))
     {
         return false;
     }
     HttpsTransportBindingElement element = transport as HttpsTransportBindingElement;
     if (((element != null) && (element.MessageSecurityVersion != null)) && (element.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion))
     {
         return false;
     }
     if (TryCreateSecurity(sbe, mode, defaultHttpTransportSecurity, isReliableSession, out security2))
     {
         bool flag2;
         WS2007HttpBinding binding2 = new WS2007HttpBinding(security2, isReliableSession);
         if (!WSHttpBinding.TryGetAllowCookiesFromTransport(transport, out flag2))
         {
             return false;
         }
         binding2.AllowCookies = flag2;
         binding = binding2;
     }
     if ((rsbe != null) && (rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11))
     {
         return false;
     }
     if ((tfbe != null) && (tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11))
     {
         return false;
     }
     return (binding != null);
 }
Exemple #19
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 SecurityToken IssueTokenWithUserNamePassword(string username, string password, string issuerUri, string appliesTo, out RequestSecurityTokenResponse RSTR, string keyType = KeyTypes.Bearer)
        {
            if (String.IsNullOrWhiteSpace(issuerUri)) throw new ArgumentNullException("issuerUri");
            if (String.IsNullOrWhiteSpace(appliesTo)) throw new ArgumentNullException("appliesTo");

            Binding binding = null;
            var WsHttpBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            // Avoid the WS-SecureConversation piece
            WsHttpBinding.Security.Message.EstablishSecurityContext = false;
            WsHttpBinding.Security.Message.NegotiateServiceCredential = false;
            WsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

            // Set our binding variable
            binding = WsHttpBinding;

            // Define the STS endpoint
            EndpointAddress endpoint = new EndpointAddress(new Uri(issuerUri));

            var factory = new WSTrustChannelFactory(binding, endpoint) { TrustVersion = TrustVersion.WSTrust13 };

            // Here is where we set the credentials (goes into the SOAP security header)
            factory.Credentials.SupportInteractive = false; // Avoid that CardSpace popup...
            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            SecurityTokenElement OnBehalfOfElement = new SecurityTokenElement(new UserNameSecurityToken("pbell", "2Federate"));
            SecurityTokenElement ActAsElement = new SecurityTokenElement(new UserNameSecurityToken("mpavlich", "2Federate"));

            // Now we define the Request for Security Token (RST)
            RequestSecurityToken RST = new RequestSecurityToken()
            {
                //identifiy who this token is for
                AppliesTo = new EndpointReference(appliesTo),
                //identify what type of request this is (Issue or Validate)
                RequestType = RequestTypes.Issue,
                //set the keytype (symmetric, asymmetric (pub key) or bearer)
                KeyType = keyType
            };

            // Create the WS-Trust channel
            IWSTrustChannelContract channel = factory.CreateChannel();

            // Send the Issue RST request
            SecurityToken token = channel.Issue(RST, out RSTR);

            return token;
        }
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count > 6)
            {
                return(false);
            }

            // collect all binding elements
            PrivacyNoticeBindingElement   privacy   = null;
            TransactionFlowBindingElement txFlow    = null;
            ReliableSessionBindingElement session   = null;
            SecurityBindingElement        security  = null;
            MessageEncodingBindingElement encoding  = null;
            HttpTransportBindingElement   transport = null;

            foreach (BindingElement element in elements)
            {
                if (element is SecurityBindingElement)
                {
                    security = element as SecurityBindingElement;
                }
                else if (element is TransportBindingElement)
                {
                    transport = element as HttpTransportBindingElement;
                }
                else if (element is MessageEncodingBindingElement)
                {
                    encoding = element as MessageEncodingBindingElement;
                }
                else if (element is TransactionFlowBindingElement)
                {
                    txFlow = element as TransactionFlowBindingElement;
                }
                else if (element is ReliableSessionBindingElement)
                {
                    session = element as ReliableSessionBindingElement;
                }
                else if (element is PrivacyNoticeBindingElement)
                {
                    privacy = element as PrivacyNoticeBindingElement;
                }
                else
                {
                    return(false);
                }
            }

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

            if (!transport.AuthenticationScheme.IsSingleton())
            {
                //multiple authentication schemes selected -- not supported in StandardBindings
                return(false);
            }

            HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement;

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

            if (null != privacy || !WSHttpBinding.TryCreate(security, transport, session, txFlow, out binding))
            {
                if (!WSFederationHttpBinding.TryCreate(security, transport, privacy, session, txFlow, out binding))
                {
                    if (!WS2007HttpBinding.TryCreate(security, transport, session, txFlow, out binding))
                    {
                        if (!WS2007FederationHttpBinding.TryCreate(security, transport, privacy, session, txFlow, out binding))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (txFlow == null)
            {
                txFlow = GetDefaultTransactionFlowBindingElement();
                if ((binding is WS2007HttpBinding) || (binding is WS2007FederationHttpBinding))
                {
                    txFlow.TransactionProtocol = TransactionProtocol.WSAtomicTransaction11;
                }
            }

            WSHttpBindingBase wSHttpBindingBase = binding as WSHttpBindingBase;

            wSHttpBindingBase.InitializeFrom(transport, encoding, txFlow, session);
            if (!wSHttpBindingBase.IsBindingElementsMatch(transport, encoding, txFlow, session))
            {
                return(false);
            }

            return(true);
        }
        // This is effectively just a copy of WSHttpBinding.TryCreate(), only it news up the 2007 version
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);
            binding = null;

            // reverse GetTransport
            HttpTransportSecurity transportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();
            UnifiedSecurityMode mode;
            if (!WSHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, out mode))
            {
                return false;
            }

            HttpsTransportBindingElement httpsBinding = transport as HttpsTransportBindingElement;
            if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
            {
                if (httpsBinding.MessageSecurityVersion.SecurityPolicyVersion != WS2007MessageSecurityVersion.SecurityPolicyVersion)
                {
                    return false;
                }
            }

            WSHttpSecurity security;
            if (WS2007HttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                WS2007HttpBinding ws2007HttpBinding = new WS2007HttpBinding(security, isReliableSession);

                bool allowCookies;
                if (!WSHttpBinding.TryGetAllowCookiesFromTransport(transport, out allowCookies))
                {
                    return false;
                }

                ws2007HttpBinding.AllowCookies = allowCookies;
                binding = ws2007HttpBinding;
            }

            if (rsbe != null && rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11)
            {
                return false;
            }

            if (tfbe != null && tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11)
            {
                return false;
            }

            return binding != null;
        }
Exemple #23
0
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            binding = null;
            if (elements.Count > 6)
            {
                return(false);
            }
            PrivacyNoticeBindingElement privacy = null;

            System.ServiceModel.Channels.TransactionFlowBindingElement tfbe = null;
            System.ServiceModel.Channels.ReliableSessionBindingElement rsbe = null;
            SecurityBindingElement        sbe       = null;
            MessageEncodingBindingElement encoding  = null;
            HttpTransportBindingElement   transport = null;

            foreach (BindingElement element7 in elements)
            {
                if (element7 is SecurityBindingElement)
                {
                    sbe = element7 as SecurityBindingElement;
                }
                else if (element7 is TransportBindingElement)
                {
                    transport = element7 as HttpTransportBindingElement;
                }
                else if (element7 is MessageEncodingBindingElement)
                {
                    encoding = element7 as MessageEncodingBindingElement;
                }
                else if (element7 is System.ServiceModel.Channels.TransactionFlowBindingElement)
                {
                    tfbe = element7 as System.ServiceModel.Channels.TransactionFlowBindingElement;
                }
                else if (element7 is System.ServiceModel.Channels.ReliableSessionBindingElement)
                {
                    rsbe = element7 as System.ServiceModel.Channels.ReliableSessionBindingElement;
                }
                else if (element7 is PrivacyNoticeBindingElement)
                {
                    privacy = element7 as PrivacyNoticeBindingElement;
                }
                else
                {
                    return(false);
                }
            }
            if (transport == null)
            {
                return(false);
            }
            if (encoding == null)
            {
                return(false);
            }
            if (((privacy != null) || !WSHttpBinding.TryCreate(sbe, transport, rsbe, tfbe, out binding)) && ((!WSFederationHttpBinding.TryCreate(sbe, transport, privacy, rsbe, tfbe, out binding) && !WS2007HttpBinding.TryCreate(sbe, transport, rsbe, tfbe, out binding)) && !WS2007FederationHttpBinding.TryCreate(sbe, transport, privacy, rsbe, tfbe, out binding)))
            {
                return(false);
            }
            if (tfbe == null)
            {
                tfbe = GetDefaultTransactionFlowBindingElement();
                if ((binding is WS2007HttpBinding) || (binding is WS2007FederationHttpBinding))
                {
                    tfbe.TransactionProtocol = TransactionProtocol.WSAtomicTransaction11;
                }
            }
            WSHttpBindingBase base2 = binding as WSHttpBindingBase;

            base2.InitializeFrom(transport, encoding, tfbe, rsbe);
            if (!base2.IsBindingElementsMatch(transport, encoding, tfbe, rsbe))
            {
                return(false);
            }
            return(true);
        }
 /// <summary>
 /// Issues security token
 /// </summary>
 /// <param name="issuerBinding">
 /// The issuer binding.
 /// </param>
 /// <param name="issuerEndpointAddress">
 /// The issuer endpoint address.
 /// </param>
 /// <param name="serviceAddress">
 /// The service address.
 /// </param>
 /// <param name="actAsToken">
 /// The act as token.
 /// </param>
 /// <returns>
 /// The security token
 /// </returns>
 public virtual SecurityToken IssueToken(WS2007HttpBinding issuerBinding, EndpointAddress issuerEndpointAddress, string serviceAddress, SecurityToken actAsToken)
 {
     var channel = this.CreateChannel(issuerBinding, issuerEndpointAddress);
     return this.IssueToken(channel, serviceAddress, actAsToken);
 }
 /// <summary>
 /// Create a trust channel
 /// </summary>
 /// <param name="issuerBinding">
 /// The issuer binding.
 /// </param>
 /// <param name="issuerEndpointAddress">
 /// The issuer endpoint address.
 /// </param>
 /// <returns>
 /// the trust channel
 /// </returns>
 public virtual IWSTrustChannelContract CreateChannel(WS2007HttpBinding issuerBinding, EndpointAddress issuerEndpointAddress)
 {
     var trustChannelFactory = new WSTrustChannelFactory(issuerBinding, issuerEndpointAddress);
     return trustChannelFactory.CreateChannel() as WSTrustChannel;
 }
Exemple #26
0
        private static string GetADFSTokenHelper(string adfsEndPoint, string userName, string password)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(adfsEndPoint + "/adfs/services/trust/13/usernamemixed"));
            var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

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

            ////This line is only if we're using self-signed certs in the installation 
            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/AdminSite"),
                TokenType = "urn:ietf:params:oauth:token-type:jwt",
                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;
        }
        private static Binding GetUserNameWSTrustBinding(SecurityMode securityMode)
        {
            var binding = new WS2007HttpBinding();
            binding.Security.Mode = securityMode;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.NegotiateServiceCredential = true;

            return binding;
        }
Exemple #28
0
        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;
        }