internal static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, PrivacyNoticeBindingElement privacy, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
 {
     WSFederationHttpSecurityMode mode;
     WSFederationHttpSecurity security2;
     bool isReliableSession = rsbe != null;
     binding = null;
     HttpTransportSecurity transportSecurity = new HttpTransportSecurity();
     if (!WSFederationHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, 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, transportSecurity, isReliableSession, out security2))
     {
         binding = new WS2007FederationHttpBinding(security2, privacy, isReliableSession);
     }
     if ((rsbe != null) && (rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11))
     {
         return false;
     }
     if ((tfbe != null) && (tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11))
     {
         return false;
     }
     return (binding != null);
 }
 public Binding Create(Endpoint serviceInterface)
 {
     System.Net.ServicePointManager.ServerCertificateValidationCallback =
         ((sender, certificate, chain, sslPolicyErrors) => true);
     var secureBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential)
                             {
                                 Name = "secure",
                                 TransactionFlow = false,
                                 HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard),
                                 MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize,
                                 MaxReceivedMessageSize = serviceInterface.MaxReceivedSize,
                                 MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Text),
                                 TextEncoding = Encoding.UTF8,
                                 ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                                 BypassProxyOnLocal = true,
                                 UseDefaultWebProxy = false
                             };
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy")=="true")
     {
         secureBinding.BypassProxyOnLocal = false;
         secureBinding.UseDefaultWebProxy = true; 
     }
     SetSecuritySettings(serviceInterface, secureBinding);
     return secureBinding;
 }
        public ActionResult Webservice()
        {
            ViewBag.Message = "Your application description page.";

            // Setup the channel factory for the call to the backend service
            var binding = new WS2007FederationHttpBinding(
            WSFederationHttpSecurityMode.TransportWithMessageCredential);
            var factory = new ChannelFactory<WebService.IService>(binding, new EndpointAddress("https://[BackendService]/Service.svc"));
            // turn off CardSpace
            factory.Credentials.SupportInteractive = false;

            // Get the token representing the logged in user
            var actAsToken = GetActAsToken();

            // Create the channel to the backend service using the acquired token
            var channel = factory.CreateChannelWithIssuedToken(actAsToken);

            // Call the service
            var serviceClaims = channel.GetClaimsPrincipal();

            // At this point, you can compare the claims the are available to the backend service with the ones available to the web app
            // See for example that the backend service has knowledge of both the logged in user and the front end app through which the user is logged in

            ViewBag.Message = "Web service call succeeded!";
            return View();
        }
Exemple #4
0
        internal static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, PrivacyNoticeBindingElement privacy, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            WSFederationHttpSecurityMode mode;
            WSFederationHttpSecurity     security2;
            bool isReliableSession = rsbe != null;

            binding = null;
            HttpTransportSecurity transportSecurity = new HttpTransportSecurity();

            if (!WSFederationHttpBinding.GetSecurityModeFromTransport(transport, transportSecurity, 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, transportSecurity, isReliableSession, out security2))
            {
                binding = new WS2007FederationHttpBinding(security2, privacy, isReliableSession);
            }
            if ((rsbe != null) && (rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11))
            {
                return(false);
            }
            if ((tfbe != null) && (tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransaction11))
            {
                return(false);
            }
            return(binding != null);
        }
        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;
        }
        static Binding CreateBinding()
        {
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);

            // only for testing on localhost
            binding.HostNameComparisonMode = HostNameComparisonMode.Exact;

            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;

            return binding;
        }
 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;
 }
        private static void CallService(SecurityToken token)
        {
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;

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

            var channel = factory.CreateChannelWithIssuedToken(token);
            channel.GetClaims().ToList().ForEach(c => Console.WriteLine(c.Value));
        }
Exemple #9
0
        private static void CallService(SecurityToken token)
        {
            "Calling Service".ConsoleYellow();

            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;

            var factory = new ChannelFactory<IClaimsService>(binding, new EndpointAddress(_serviceAddress));
            factory.Credentials.SupportInteractive = false;
            factory.Credentials.UseIdentityConfiguration = true;
            var proxy = factory.CreateChannelWithIssuedToken(token);

            var id = proxy.GetIdentity();
            Helper.ShowIdentity(id);
        }
        private static IService CreateProxy()
        {
            // request identity token from ADFS
            SecurityToken token = RequestIdentityToken();

            // set up factory and channel
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            binding.Security.Message.EstablishSecurityContext = false;
            
            var factory = new ChannelFactory<IService>(binding, _serviceEndpoint);
            factory.Credentials.SupportInteractive = false;

            // enable WIF on channel factory
            factory.ConfigureChannelFactory();

            return factory.CreateChannelWithIssuedToken(token);
        }
        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;
        }
        static void Main(string[] args)
        {
            var jwt = GetJwt();
            var xmlToken = WrapJwt(jwt);

            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            binding.HostNameComparisonMode = HostNameComparisonMode.Exact;
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;

            var factory = new ChannelFactory<IService>(
                binding,
                new EndpointAddress("https://localhost:44335/token"));

            var channel = factory.CreateChannelWithIssuedToken(xmlToken);
            
            Console.WriteLine(channel.Ping());
        }
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, PrivacyNoticeBindingElement privacy, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);

            binding = null;

            // reverse GetTransport
            HttpTransportSecurity        transportSecurity = new HttpTransportSecurity();
            WSFederationHttpSecurityMode mode;

            if (!WSFederationHttpBinding.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);
                }
            }

            WSFederationHttpSecurity security;

            if (WS2007FederationHttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                binding = new WS2007FederationHttpBinding(security, privacy, isReliableSession);
            }

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

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

            return(binding != null);
        }
        private void _btnCallService_Click(object sender, RoutedEventArgs e)
        {
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;

            var ep = new EndpointAddress("https://" + Constants.WebHost + "/webservicesecurity/soap.svc/bearer");

            var factory = new ChannelFactory<IService>(binding, ep);
            factory.Credentials.SupportInteractive = false;
            factory.ConfigureChannelFactory();

            var channel = factory.CreateChannelWithIssuedToken(RSTR.SecurityToken);
            var claims = channel.GetClientIdentity();
            
            var sb = new StringBuilder(128);
            claims.ForEach(c => sb.AppendFormat("{0}\n {1}\n\n", c.ClaimType, c.Value));
            _txtDebug.Text = sb.ToString();
        }
        private static void CallService(SecurityToken token)
        {
            //var serviceEndpoint = "https://" + "adfs.leastprivilege.vm" + "/rp/service.svc";
            var serviceEndpoint = "https://" + "localhost:44305" + "/service.svc";
            
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;

            var factory = new ChannelFactory<IClaimsService>(
                binding,
                new EndpointAddress(serviceEndpoint));
            factory.Credentials.SupportInteractive = false;

            var channel = factory.CreateChannelWithIssuedToken(token);
            var claims = channel.GetClaims();

            claims.ForEach(c => Console.WriteLine("{0}\n {1}\n\n", c.Type, c.Value));
        }
        private static SecurityToken IssueLocalSecurityToken(SecurityToken foreignToken, string RP_Endpoint, string appliesTo, out RequestSecurityTokenResponse RSTR, string keyType = KeyTypes.Bearer)
        {
            if (String.IsNullOrWhiteSpace(RP_Endpoint)) throw new ArgumentNullException("RP_Endpoint");

            Binding binding = null;

            // Authenticate with a SAML Bearer token
            var WsHttpBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            WsHttpBinding.Security.Message.EstablishSecurityContext = false;
            WsHttpBinding.Security.Message.NegotiateServiceCredential = false;
            WsHttpBinding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;
            binding = WsHttpBinding;

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

            var factory = new WSTrustChannelFactory(binding, endpoint) { TrustVersion = TrustVersion.WSTrust13 };
            factory.Credentials.SupportInteractive = false; // avoid that Cardspace dialog

            // Now we define the Request for Security Token (RST)
            RequestSecurityToken RST = new RequestSecurityToken()
            {
                //identifiy which local token we want
                AppliesTo = new EndpointReference(appliesTo),
                //identify what type of request this is (Issue or Validate)
                RequestType = RequestTypes.Issue,
                //set what kind of token we want returned (appliesTo will override this)
                TokenType = tokenType,
                //set the keytype (symmetric, asymmetric (pub key) or bearer - null = Sender Vouches)
                KeyType = null
            };

            //create the channel (using the SAML token received from the WSC)
            IWSTrustChannelContract channel = factory.CreateChannelWithIssuedToken(foreignToken);

            //send the token issuance command
            SecurityToken token = channel.Issue(RST, out RSTR);

            return token;
        }
Exemple #17
0
        private static SecurityToken ConvertToToken(string xml)
        {
            WS2007FederationHttpBinding binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential,
                false);
            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(binding, new EndpointAddress("https://null-EndPoint"));
            factory.TrustVersion = TrustVersion.WSTrustFeb2005;

            Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel trustChannel = (Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel)factory.CreateChannel();

            RequestSecurityTokenResponse response = trustChannel.WSTrustResponseSerializer.CreateInstance();
            response.RequestedSecurityToken = new RequestedSecurityToken(LoadXml(xml).DocumentElement);
            response.IsFinal = true;

            RequestSecurityToken requestToken = new RequestSecurityToken(WSTrustFeb2005Constants.RequestTypes.Issue);
            requestToken.KeyType = WSTrustFeb2005Constants.KeyTypes.Symmetric;

            return trustChannel.GetTokenFromResponse(requestToken, response);
        }
        private static RequestSecurityTokenResponse ValidateSecurityToken(SecurityToken foreignToken, string RP_Endpoint, string keyType = KeyTypes.Bearer)
        {
            if (String.IsNullOrWhiteSpace(RP_Endpoint)) throw new ArgumentNullException("RP_Endpoint");

            Binding binding = null;

            // Using a SAML bearer token
            var WsHttpBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            WsHttpBinding.Security.Message.EstablishSecurityContext = false;
            WsHttpBinding.Security.Message.NegotiateServiceCredential = false;
            WsHttpBinding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;
            binding = WsHttpBinding;

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

            var factory = new WSTrustChannelFactory(binding, endpoint) { TrustVersion = TrustVersion.WSTrust13 };
            factory.Credentials.SupportInteractive = false; // Avoid that CardSpace popup...
            IWSTrustChannelContract channel = factory.CreateChannelWithIssuedToken(foreignToken); // When we create the Channel we specify the SAML token received from the WSC

            // Build the RST
            RequestSecurityToken RST = new RequestSecurityToken()
            {
                //identify what type of request this is (Issue or Validate)
                RequestType = RequestTypes.Validate
            };

            // Send the Validate RST
            RequestSecurityTokenResponse RSTR = channel.Validate(RST);

            return RSTR;
        }
Exemple #19
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);
        }
        private static IClaimsService GetServiceProxy(SecurityToken token)
        {
            var serviceAddress = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Reply + "service.svc";
            
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;

            var factory = new ChannelFactory<IClaimsService>(
                binding,
                new EndpointAddress(serviceAddress));
            factory.Credentials.SupportInteractive = false;

            var channel = factory.CreateChannelWithIssuedToken(token);
            return channel;
        }
        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);
        }
        /// <summary>
        /// Issues security token
        /// </summary>
        /// <param name="binding">
        /// The binding.
        /// </param>
        /// <param name="serviceAddress">
        /// The service address.
        /// </param>
        /// <param name="actAsToken">
        /// The act as token.
        /// </param>
        /// <returns>
        /// The security token
        /// </returns>
        /// <exception cref="ApplicationException">
        /// </exception>
        public virtual SecurityToken IssueToken(WS2007FederationHttpBinding binding, string serviceAddress, SecurityToken actAsToken)
        {
            var issuerEndpointAddress = binding.Security.Message.IssuerAddress;
            var issuerBinding = binding.Security.Message.IssuerBinding as WS2007HttpBinding;
            if (issuerBinding == null)
            {
                throw new ApplicationException("Unable to get WS2007HttpBinding");
            }

            var token = this.IssueToken(issuerBinding, issuerEndpointAddress, serviceAddress, actAsToken);
            return token;
        }
Exemple #23
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;
        }
        internal new static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, PrivacyNoticeBindingElement privacy, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
        {
            bool isReliableSession = (rsbe != null);
            binding = null;

            // reverse GetTransport
            HttpTransportSecurity transportSecurity = new HttpTransportSecurity();
            WSFederationHttpSecurityMode mode;
            if (!WSFederationHttpBinding.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;
                }
            }

            WSFederationHttpSecurity security;
            if (WS2007FederationHttpBinding.TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
            {
                binding = new WS2007FederationHttpBinding(security, privacy, isReliableSession);
            }

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

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

            return binding != null;
        }