Exemplo n.º 1
0
        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());
        }
Exemplo n.º 2
0
        public DataEntityCollectionDTO RetrieveEntityByNameQuery(string queryName, Dictionary <string, object> parameters,
                                                                 SecurityToken sessionToken)
        {
            SecuritySummary securitySummary = new SecuritySummary();
            CallStatus      callStatus      = new CallStatus();

            using (ChannelFactory <IDataEntityIO> factory = GetApplicationServerChannelFactory(_applicationServerAddress)
                   )
            {
                factory.Credentials.UseIdentityConfiguration = true;
                IDataEntityIO secureConnection = factory.CreateChannelWithIssuedToken(sessionToken);

                DataEntityCollectionDTO entities = secureConnection.RunNamedQuery(queryName, parameters,
                                                                                  ref securitySummary, ref callStatus);

                if (callStatus.Result == CallStatusenumCallResult.Success)
                {
                    return(entities);
                }

                StringBuilder sb = new StringBuilder();
                foreach (ValidationError error in callStatus.Messages)
                {
                    sb.AppendLine(error.Message);
                }
                throw new Exception("Call did not complete successfully" + Environment.NewLine + sb);
            }

            //TODO: CONTINUE WITH THIS METHOD SIMILAR TO StaffQuery
            return(null);
        }
Exemplo n.º 3
0
        public DataEntityCollectionDTO RetrieveEntityById(string entityName, Guid entityId, SecurityToken sessionToken)
        {
            SecuritySummary securitySummary = new SecuritySummary();
            CallStatus callStatus = new CallStatus();

            using (ChannelFactory<IDataEntityIO> factory = GetApplicationServerChannelFactory(_applicationServerAddress))
            {
                factory.Credentials.UseIdentityConfiguration = true;
                IDataEntityIO secureConnection = factory.CreateChannelWithIssuedToken(sessionToken);

                List<string> fieldNames = GetFields(entityName);

                DataEntityCollectionDTO entities = secureConnection.ReadEntity(
                   entityId,
                   entityName,
                   fieldNames, ref securitySummary, ref callStatus);

                if (callStatus.Result == CallStatusenumCallResult.Success) return entities;

                StringBuilder sb = new StringBuilder();
                foreach (ValidationError error in callStatus.Messages)
                {
                    sb.AppendLine(error.Message);
                }
                throw new Exception("Call did not complete successfully" + Environment.NewLine + sb);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates the instance internal.
        /// </summary>
        /// <typeparam name="TServiceContract">The type of the service contract.</typeparam>
        /// <param name="channelFactory">The channel factory.</param>
        /// <returns></returns>
        private TServiceContract CreateInstanceInternalClaims <TServiceContract>(ChannelFactory <TServiceContract> channelFactory)
        {
            foreach (var operation in channelFactory.Endpoint.Contract.Operations)
            {
                var dataContractSerializerOperationBehavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (dataContractSerializerOperationBehavior == null)
                {
                    dataContractSerializerOperationBehavior = new DataContractSerializerOperationBehavior(operation);

                    if (!operation.Behaviors.Contains(dataContractSerializerOperationBehavior))
                    {
                        operation.Behaviors.Add(dataContractSerializerOperationBehavior);
                    }
                }
                dataContractSerializerOperationBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
            }

            // Add channelFactory.Endpoint Behaviors
            if (channelFactory.Endpoint.Behaviors.Find <CallerContextBehavior>() == null)
            {
                var endpointBehavior = new CallerContextBehavior();
                channelFactory.Endpoint.Behaviors.Add(endpointBehavior);
            }

#if DEBUG
            if (channelFactory.Endpoint.Behaviors.Find <ProfilerEndpointBehavior>() == null)
            {
                var profilerBehaviour = new ProfilerEndpointBehavior();
                channelFactory.Endpoint.Behaviors.Add(profilerBehaviour);
            }
#endif

            // Add channelFactory.Endpoint.Contract.Operations Behaviors

            // None

            /*
             *
             * var operationBehaviours = new List<IOperationBehavior>();
             *
             * foreach (var operationBehavior in operationBehaviors)
             * {
             *  foreach (var operation in channelFactory.Endpoint.Contract.Operations)
             *  {
             *      if (!operation.Behaviors.Contains(operationBehavior))
             *      {
             *          operation.Behaviors.Add(operationBehavior);
             *      }
             *  }
             * }
             */

            if (channelFactory.Credentials != null)
            {
                channelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
            }

            return(channelFactory.CreateChannelWithIssuedToken(GetSecurityTokenDirectFromLocalSts()));
        }
Exemplo n.º 5
0
        public T GetService <T>(string endpointConfigurationName)
        {
            var factory = new ChannelFactory <T>(endpointConfigurationName);

            _activeServices.Add(factory);

            return(factory.CreateChannelWithIssuedToken(_authToken));
        }
        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();
        }
Exemplo n.º 7
0
        /// <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();
                }
            }
        }
Exemplo n.º 8
0
        public void Save(DataEntityCollectionDTO entitys, SecurityToken sessionToken, string applicationServerURL, List <string> saveScope)
        {
            CallStatus callStatus = new CallStatus();

            using (ChannelFactory <IDataEntityIO> factory = GetApplicationServerChannelFactory(applicationServerURL))
            {
                DataEntityDTOChangeBatchCollection changes = new DataEntityDTOChangeBatchCollection
                {
                    Batches = new List <DataEntityDTOChangeBatch>()
                };
                DataEntityDTO.DataModelTypeDTO dataModelType = new DataEntityDTO.DataModelTypeDTO {
                    SchemaName = "dbo", DataModelPurpose = "BusinessDataModel"
                };
                changes.DataModelType = dataModelType;
                DataEntityDTOChangeBatch batch = new DataEntityDTOChangeBatch {
                    EntitiesToSave = entitys
                };
                DataEntitySaveContext batchSaveContext = new DataEntitySaveContext();
                List <string>         alternateKeys    = new List <string>();
                List <string>         batchSaveScope   = new List <string>();
                if (_changedFields.Any())
                {
                    batchSaveScope = _changedFields;
                }
                else if (saveScope.Any())
                {
                    batchSaveScope = saveScope;
                }
                batchSaveContext.SaveScope             = batchSaveScope;
                batchSaveContext.AlternateKeyFields    = alternateKeys;
                batchSaveContext.CustomWorkflows       = new List <WorkflowPackage>();
                batchSaveContext.CustomDeleteWorkflows = new List <WorkflowPackage>();
                batch.SaveContext = batchSaveContext;
                changes.Batches.Add(batch);

                factory.Credentials.UseIdentityConfiguration = true;
                IDataEntityIO secureConnection = factory.CreateChannelWithIssuedToken(sessionToken);
                secureConnection.SaveEntityCollection(changes, ref callStatus);

                if (callStatus.Result == CallStatusenumCallResult.Success)
                {
                    return;
                }

                StringBuilder sb = new StringBuilder();
                foreach (ValidationError error in callStatus.Messages)
                {
                    sb.AppendLine(error.Message);
                }

                throw new Exception("Call did not complete successfully" + Environment.NewLine + sb);
            }
        }
Exemplo n.º 9
0
        internal void Save(DataEntityCollectionDTO entitys, SecurityToken sessionToken)
        {
            // Almost all iSIMS calls fill a callStatus response message in with status and error messages.
            CallStatus callStatus = new CallStatus();

            // Create a communication channel factory to communicate with the iSIMS application server
            using (ChannelFactory <IDataEntityIO> factory = GetApplicationServerChannelFactory())
            {
                // Because our communication now will be secured using our Identity Token we need to use some WIF extension methods to make sure the identity token
                // is sent as a Cookie on the SOAP call that WCF will be generating.
                factory.Credentials.UseIdentityConfiguration = true;
                IDataEntityIO secureConnection = factory.CreateChannelWithIssuedToken(sessionToken);

                DataEntityDTOChangeBatchCollection changes = new DataEntityDTOChangeBatchCollection
                {
                    Batches = new List <DataEntityDTOChangeBatch>()
                };
                DataEntityDTO.DataModelTypeDTO dataModelType = new DataEntityDTO.DataModelTypeDTO {
                    SchemaName = "dbo", DataModelPurpose = "BusinessDataModel"
                };
                changes.DataModelType = dataModelType;
                DataEntityDTOChangeBatch batch = new DataEntityDTOChangeBatch {
                    EntitiesToSave = entitys
                };
                DataEntitySaveContext batchSaveContext = new DataEntitySaveContext();
                List <string>         alternateKeys    = new List <string>();
                // Simplest thing to do is declare which field we believe we have changed
                List <string> batchSaveScope = new List <string> {
                    "Learner.PreferredForename"
                };
                List <WorkflowPackage> customWorkflows = new List <WorkflowPackage>();
                batchSaveContext.SaveScope             = batchSaveScope;
                batchSaveContext.AlternateKeyFields    = alternateKeys;
                batchSaveContext.CustomWorkflows       = customWorkflows;
                batchSaveContext.CustomDeleteWorkflows = new List <WorkflowPackage>();
                batch.SaveContext = batchSaveContext;
                changes.Batches.Add(batch);
                secureConnection.SaveEntityCollection(changes, ref callStatus);



                // Handle an unsuccessful call.
                if (callStatus.Result != CallStatusenumCallResult.Success)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (ValidationError error in callStatus.Messages)
                    {
                        sb.AppendLine(error.Message);
                    }
                    throw new Exception("Call did not complete successfully" + Environment.NewLine + sb);
                }
            }
        }
Exemplo n.º 10
0
        public static string CallCreate(ChannelFactory <Resource> resourceFactory, Uri thisUrl, string smlDomain, int assuranceLevel, CreateRequest request, IMessageMetadata messageMetadata)
        {
            STARTLibrary.accesspointService.Resource ws = null;

            try
            {
                var serviceMetadata = !string.IsNullOrEmpty(smlDomain) ?
                                      ServiceMetadata.FromSml(smlDomain, request) :
                                      ServiceMetadata.FromKnownEndpoint(resourceFactory);

                //NOTE: if you want to debug and send to "wrong" address, change below:
                //var test1 = ServiceMetadata.FromSml(smlDomain, request); //henter metadata fra SML
                //var test2 = ServiceMetadata.FromKnownEndpoint(resourceFactory);
                //var test3 = new ServiceMetadata()
                //    {
                //        Address = new Uri("https://ehf.fylkesmannen.no/oxalis"), //factory.Endpoint.Address.Uri,
                //        Certificate = resourceFactory.Credentials.ServiceCertificate.DefaultCertificate
                //    };
                //serviceMetadata = test1;

                if (serviceMetadata.Certificate == null)
                {
                    throw new ArgumentException("Certificate required (both for custom validation and for authenticationMode \"MutualCertificate\").");
                }

                SetExpectedServiceCertificate(resourceFactory, serviceMetadata.Certificate);

                X509Certificate2 clientCertificate = resourceFactory.Credentials.ClientCertificate.Certificate;

                Saml2SecurityToken token = AccessPointToken.ClaimsToSaml2SenderVouchesToken(
                    AccessPointToken.MakeClaims(request.SenderIdentifier.Value, assuranceLevel),
                    thisUrl.AbsoluteUri, clientCertificate);

                //NOTE: changed when upgrading to .NET 4.5:
                //ws = resourceFactory.CreateChannelWithIssuedToken(new EndpointAddress(thisUrl, resourceFactory.Endpoint.Address.Identity), token);
                ws = resourceFactory.CreateChannelWithIssuedToken(token, new EndpointAddress(thisUrl, resourceFactory.Endpoint.Address.Identity));

                var response = ws.Create(request);
                return("Document sent.");
            }
            catch (Exception exception)
            {
                throw exception;
            }
            finally
            {
                if (ws is IDisposable)
                {
                    (ws as IDisposable).Dispose();
                }
            };
        }
Exemplo n.º 11
0
        private void CreateClient(EndpointAddress endpointAdress)
        {
            var rest = ClientFactory.Endpoint.Behaviors.Find <RestTokenHandler>();

            if (rest != null)
            {
                var tokenManager = FindTokenManager();
                RuntimeFactory.Current.GetStateStorageContainer().TryAddStorageItem(tokenManager);
                Client = ClientFactory.CreateChannel(endpointAdress);
            }
            else
            {
                if (ConfigurationManagerHelper.GetValueOnKey("stardust.RelayToken") == "true")
                {
                    if (BootstrapContext != null)
                    {
                        Client = ClientFactory.CreateChannelWithIssuedToken(BootstrapContext.SecurityToken);
                        return;
                    }
                }
                if (!(ClientFactory.Endpoint.Binding is WS2007FederationHttpBinding))
                {
                    Client = ClientFactory.CreateChannel(endpointAdress);
                    return;
                }
                if (BootstrapContext.IsInstance())
                {
                    Client = ClientFactory.CreateChannelWithIssuedToken(GetTokenOnBehalfOf(), endpointAdress);
                }
                else if (UseSecureChannel)
                {
                    Client = ClientFactory.CreateChannelWithIssuedToken(GetToken(), endpointAdress);
                }
                else
                {
                    Client = ClientFactory.CreateChannel(endpointAdress);
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Example of retrieving some data from the application server. In this case we will use the ReadEnity call to retrieve data for a single Learner entity.
        ///
        /// This illustrates the method of constructing a single entity query, and handling the results that are returned. It also illustrates the use of the CallStatus
        /// structure to retrieve information about the call, and any failures that occured.
        /// </summary>
        /// <param name="learnerid"></param>
        /// <param name="sessionToken"></param>
        internal DataEntityCollectionDTO RetrieveSingleLearnerById(string learnerid, SecurityToken sessionToken)
        {
            // The security summary will be filled with any notifications of data fields which were removed by the security protocols prior to being sent to the recipient. This
            // enables you to see whether your data has been redacted before you got to see it.
            SecuritySummary securitySummary = new SecuritySummary();

            // Almost all iSIMS calls fill a callStatus response message in with status and error messages.
            CallStatus callStatus = new CallStatus();

            // Create a communication channel factory to communicate with the iSIMS application server
            using (ChannelFactory <IDataEntityIO> factory = GetApplicationServerChannelFactory())
            {
                // Because our communication now will be secured using our Identity Token we need to use some WIF extension methods to make sure the identity token
                // is sent as a Cookie on the SOAP call that WCF will be generating.
                factory.Credentials.UseIdentityConfiguration = true;
                IDataEntityIO secureConnection = factory.CreateChannelWithIssuedToken(sessionToken);
                Guid          studentId        = new Guid(learnerid);

                // Construct a query to read a specific entity from SIMS8
                DataEntityCollectionDTO entities = secureConnection.ReadEntity( // Tell it which specific unique entity we want to fetch
                    studentId,                                                  // Tell it what type of entity this is
                    "Learner",                                                  // Tell it what scope of data we want to get back from the call.
                    new List <string>(new[]
                {
                    // The surname and forename
                    "Learner.LegalSurname",
                    "Learner.LegalForename",
                    "Learner.PreferredForename",
                    // The Unique Pupil Number
                    "Learner.UPN",
                    // The Learners Addresses, start date. Note that there are many Addresses attached to a single Learner
                    "Learner.LearnerAddresses.StartDate",
                    // The Learners Addresses, Post Code
                    "Learner.LearnerAddresses.Address.PostCode"
                }), ref securitySummary, ref callStatus);

                // Handle an unsuccessful call.
                if (callStatus.Result != CallStatusenumCallResult.Success)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (ValidationError error in callStatus.Messages)
                    {
                        sb.AppendLine(error.Message);
                    }
                    throw new Exception("Call did not complete successfully" + Environment.NewLine + sb);
                }
                return(entities);
            }
        }
        private void ConnectToWcfService()
        {
            if (connected)
            {
                return;
            }
            if (token == null)
            {
                if (useActAs)
                {
                    token = AdfsHelper.GetActAsToken(idpEndpoint, realm, serviceUserName, servicePassword);
                }
                else
                {
                    token = AdfsHelper.GetSecurityToken(idpEndpoint, realm, serviceUserName, servicePassword);
                }
            }

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

            // create factory and enable WIF plumbing
            factory = new ChannelFactory <T>(binding, serviceAddress);
            InvokeConfigureChannel();
            try
            {
                factory.Credentials.ServiceCertificate.Authentication.RevocationMode            = X509RevocationMode.NoCheck;
                factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

                //TODO Upgrade 4.5 - http://social.msdn.microsoft.com/Forums/vstudio/en-US/9cffe4ea-5a0d-4729-9eb1-b56629b175dc/configurechannelfactory-in-net-45?forum=Geneva
                //factory.ConfigureChannelFactory();

                factory.Credentials.SupportInteractive = false;

                channel = factory.CreateChannelWithIssuedToken(token);
                SetupWcfHeader();
                connected = true;
            }
            catch (Exception)
            {
                factory.Abort();
                throw;
            }
        }
Exemplo n.º 14
0
        public static IUSIService OpenWithM2M()
        {
            SecurityToken token = GetStsToken(tokenLifeTimeMinutes: 60);

            var clientSection   = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");
            var endpointElement = clientSection.Endpoints.Cast <ChannelEndpointElement>().First(endpoint =>
                                                                                                "UsiCreateServiceReference.IUSIService".Equals(endpoint.Contract, StringComparison.InvariantCultureIgnoreCase));

            if (endpointElement == null)
            {
                throw new Exception("No endpoint matching service contract was found");
            }

            var channelFactory = new ChannelFactory <IUSIService>(endpointElement.Name);

            channelFactory.Open();

            return(channelFactory.CreateChannelWithIssuedToken(token));
        }
Exemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T">T is the interface the service provider exposes.</typeparam>
        /// <param name="token">GenericXmlSecurityToken containing a saml2SecurityToken</param>
        /// <param name="clientCertificate"></param>
        /// <param name="serviceCertificate"></param>
        /// <param name="serviceEndpointAddress"></param>
        /// <returns></returns>
        public static T CreateChannelWithIssuedToken <T>(SecurityToken token, X509Certificate2 clientCertificate, X509Certificate2 serviceCertificate, EndpointAddress serviceEndpointAddress)
        {
            bool sslEnabled = serviceEndpointAddress.Uri.Scheme.ToLowerInvariant() == "https";

            ChannelFactory <T> echoServiceFactory = new ChannelFactory <T>(new ServiceproviderBinding(sslEnabled), serviceEndpointAddress);


            echoServiceFactory.Credentials.ClientCertificate.Certificate = clientCertificate;

            //Issuedtoken binding information needs to be set, even though it aint used.
            echoServiceFactory.Credentials.IssuedToken.LocalIssuerBinding = new SecurityTokenServiceBinding();
            echoServiceFactory.Credentials.IssuedToken.LocalIssuerAddress = new EndpointAddress(new Uri("http://NotAnUrlAndNotToBeUsed"));

            echoServiceFactory.Credentials.ServiceCertificate.DefaultCertificate = serviceCertificate;

            FederatedClientCredentials.ConfigureChannelFactory(echoServiceFactory);

            return(echoServiceFactory.CreateChannelWithIssuedToken(token));
        }
        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);
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
        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());
        }
        public static string CallCreate(ChannelFactory <STARTLibrary.accesspointService.Resource> resourceFactory,
                                        Uri thisUrl, string smlDomain, int assuranceLevel, CreateRequest request)
        {
            STARTLibrary.accesspointService.Resource ws = null;

            Helper help = new Helper();

            try
            {
                ServiceMetadata metadata = !string.IsNullOrEmpty(smlDomain) ?
                                           ServiceMetadata.FromSml(smlDomain, request) :
                                           ServiceMetadata.FromKnownEndpoint(resourceFactory);
                if (metadata.Certificate == null)
                {
                    throw new ArgumentException("Certificate required (both for custom validation and for authenticationMode \"MutualCertificate\").");
                }

                SetExpectedServiceCertificateNew(resourceFactory, metadata.Certificate);

                X509Certificate2 clientCertificate = resourceFactory.Credentials.ClientCertificate.Certificate;

                Saml2SecurityToken token = AccessPointToken.ClaimsToSaml2SenderVouchesToken(
                    AccessPointToken.MakeClaims(request.SenderIdentifier.Value, assuranceLevel),
                    thisUrl.AbsoluteUri, clientCertificate);

                ws = resourceFactory.CreateChannelWithIssuedToken(new EndpointAddress(thisUrl, resourceFactory.Endpoint.Address.Identity), token);

                ws.Create(request);
                return("Document sent.");
            }
            catch (Exception)
            {
                throw help.MakePeppolException("bden:ServerError", "ServerError");
            }
            finally
            {
                if (ws is IDisposable)
                {
                    (ws as IDisposable).Dispose();
                }
            };
        }
Exemplo n.º 20
0
        private static string CallService_IssuedToken(SecurityToken token)
        {
            // Creating the channel and calling it
            var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);

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

            var serviceEpAddress = ConfigurationManager.AppSettings["serviceEpAddress"].ToString();
            var factory          = new ChannelFactory <IService1>(binding, new EndpointAddress(serviceEpAddress));

            // Create a channel
            IService1 client = factory.CreateChannelWithIssuedToken(token);

            // Invoke the service operation
            var response = client.GetData(12);

            ((IClientChannel)client).Close();

            return(response);
        }
        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();
        }
Exemplo n.º 22
0
        private static void CallService(SecurityToken token)
        {
            var serviceEndpoint = "https://" + "adfs.leastprivilege.vm" + "/rp/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));
        }
        public static T GetClaimAppService <T>(SecurityToken securityToken, string serviceAddress) where T : class
        {
            try
            {
                var binding =
                    new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
                binding.Security.Message.EstablishSecurityContext = false;
                binding.Security.Message.IssuedKeyType            = SecurityKeyType.BearerKey;

                var factory = new ChannelFactory <T>(
                    binding,
                    new EndpointAddress(new Uri(serviceAddress), EndpointIdentity.CreateDnsIdentity("IdentifyDefaultSigning")));
                factory.Credentials.SupportInteractive = false;

                var channel = factory.CreateChannelWithIssuedToken(securityToken);
                return(channel);
            }
            catch (Exception ex)
            {
                Logging.Instance.Error(ex, "Error while execute remote operation");
                throw;
            }
        }
Exemplo n.º 24
0
        // GET: Home
        public ActionResult Index()
        {
            string response  = String.Empty;
            string exception = String.Empty;

            try
            {
                //creating the channel and calling it

                WS2007FederationHttpBinding federationBinding = new WS2007FederationHttpBinding();
                federationBinding.Security.Mode = WSFederationHttpSecurityMode.TransportWithMessageCredential;
                federationBinding.Security.Message.EstablishSecurityContext = false;

                EndpointAddress wcfServiceEndpoint    = new EndpointAddress(Program.WCFAddress);
                ChannelFactory <ITestService> factory = new ChannelFactory <ITestService>(federationBinding, wcfServiceEndpoint);
                factory.Credentials.SupportInteractive       = false;
                factory.Credentials.UseIdentityConfiguration = true;

                var token = GetSecurityToken();

                // Create a channel.
                ITestService client = factory.CreateChannelWithIssuedToken(token);
                response = client.SayHello();
                ((IClientChannel)client).Close();
            }
            catch (Exception ex)
            {
                response  = ex.Message;
                exception = ex.StackTrace;
            }

            ViewBag.ServiceResult = response;
            ViewBag.Exception     = exception;


            return(View());
        }
Exemplo n.º 25
0
        public bool SaveFileToDocumentStore(string documentUrl, byte[] content)
        {
            var callStatus = new CallStatus();

            using (ChannelFactory <IDataEntityIO> factory = GetApplicationServerChannelFactory(_applicationServerAddress))
            {
                factory.Credentials.UseIdentityConfiguration = true;
                IDataEntityIO secureConnection = factory.CreateChannelWithIssuedToken(_sessionToken);

                secureConnection.SaveFileToDocumentStore(documentUrl, content, ref callStatus);

                if (callStatus.Result == CallStatusenumCallResult.Success)
                {
                    return(true);
                }

                var sb = new StringBuilder();
                foreach (var error in callStatus.Messages)
                {
                    sb.AppendLine(error.Message);
                }
                throw new Exception("Upload Document Failed !!!" + Environment.NewLine + sb);
            }
        }
Exemplo n.º 26
0
        public string GetDocumentStoreUrl(string propertyName, Guid storeId)
        {
            var callStatus = new CallStatus();

            using (ChannelFactory <IDataEntityIO> factory = GetApplicationServerChannelFactory(_applicationServerAddress))
            {
                factory.Credentials.UseIdentityConfiguration = true;
                IDataEntityIO secureConnection = factory.CreateChannelWithIssuedToken(_sessionToken);

                string documentUrl = secureConnection.GetDocumentStoreURL(propertyName, storeId, ref callStatus);

                if (callStatus.Result == CallStatusenumCallResult.Success)
                {
                    return(documentUrl);
                }

                var sb = new StringBuilder();
                foreach (var error in callStatus.Messages)
                {
                    sb.AppendLine(error.Message);
                }
                throw new Exception("Document Store Directory Does not exists !!!" + Environment.NewLine + sb);
            }
        }
Exemplo n.º 27
0
        private static void CallMyService(string jwtToken)
        {
            var xmlToken = WrapJwt(jwtToken);

            var factory = new ChannelFactory <IMyService>(ServiceBinding.CreateBinding(),
                                                          new EndpointAddress(Config.ServiceEndpoint));

            var myService = factory.CreateChannelWithIssuedToken(xmlToken);

            // Call MyService
            string dataId = "001";

            WriteLine($"Create data: {dataId}", ConsoleColor.White);
            try
            {
                // Call MyService.CreateData
                string result = myService.CreateData(dataId);
                WriteLine($"  {result}", ConsoleColor.Green);
            }
            catch (Exception ex)
            {
                WriteLine($"  Error: {ex.Message}", ConsoleColor.Red);
            }
            Console.WriteLine();

            // Read
            WriteLine($"Read data: {dataId}", ConsoleColor.White);
            try
            {
                // Call MyService.ReadData
                string result = myService.ReadData(dataId);
                WriteLine($"  {result}", ConsoleColor.Green);
            }
            catch (Exception ex)
            {
                WriteLine($"  Error: {ex.Message}", ConsoleColor.Red);
            }
            Console.WriteLine();

            // Update
            WriteLine($"Update data: {dataId}", ConsoleColor.White);
            try
            {
                // Call MyService.UpdateData
                string result = myService.UpdateData(dataId);
                WriteLine($"  {result}", ConsoleColor.Green);
            }
            catch (Exception ex)
            {
                WriteLine($"  Error: {ex.Message}", ConsoleColor.Red);
            }
            Console.WriteLine();

            // Delete
            WriteLine($"Delete data: {dataId}", ConsoleColor.White);
            try
            {
                // Call MyService.DeleteData
                string result = myService.DeleteData(dataId);
                WriteLine($"  {result}", ConsoleColor.Green);
            }
            catch (Exception ex)
            {
                WriteLine($"  Error: {ex.Message}", ConsoleColor.Red);
            }
            Console.WriteLine();
        }
Exemplo n.º 28
0
        /// <summary>
        /// Creates a federated channel.
        /// Security tokens are cached, to eliminate the need for contacting the STS every time.
        /// </summary>
        /// <param name="channelFactory">
        /// The channel factory.
        /// </param>
        /// <typeparam name="T">
        /// The service interface
        /// </typeparam>
        /// <returns>
        /// A new federated channel
        /// </returns>
        protected virtual T CreateFederatedChannel <T>(ChannelFactory <T> channelFactory)
        {
            var token = GetSecurityToken(channelFactory);

            return(channelFactory.CreateChannelWithIssuedToken(token));
        }
Exemplo n.º 29
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);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Use this method if you want to send to a custom access-point (debug)
        /// </summary>
        /// <param name="createRequest">SOAP-request to send to accesspoint</param>
        /// <param name="sender">sender-id, sample:9908:974763907</param>
        /// <param name="receiver">receiver-id, sample:9908:974763907</param>
        /// <param name="serviceMetadata">Servicemetadata containing endpoint and certificates</param>
        /// <returns></returns>
        public SendResult SendDocument(CreateRequest createRequest, string sender, string receiver, ServiceMetadata serviceMetadata)
        {
            var start = DateTime.Now;

            try
            {
                Log.Info("Start SendInvoice...");
                if (serviceMetadata == null)
                {
                    throw new ArgumentNullException("serviceMetadata", "serviceMetadata cannot be null");
                }
                if (serviceMetadata.Certificate == null)
                {
                    throw new ArgumentException("Certificate required (both for custom validation and for authenticationMode \"MutualCertificate\").");
                }
                if (string.IsNullOrEmpty(sender))
                {
                    throw new ArgumentNullException("sender", "sender cannot be null. samlpevalue: 9908:974763907");
                }
                if (string.IsNullOrEmpty(receiver))
                {
                    throw new ArgumentNullException("receiver", "receiver cannot be null. samlpevalue: 9908:974763907");
                }

                //Recreating channelfactory... this is resource-intensive, and should be cached. recreating since certificate is readonly after channel is open.
                Log.InfoFormat("Recreating channelfactory for ep {0} using certificate {1}", serviceMetadata.Address.AbsoluteUri, serviceMetadata.Certificate.FriendlyName);
                _channelFactory = Utilities.CreateResourceChannelFactory <Resource>(_peppolEndpointName, _clientCertificate, _serviceCertificate);

                //1. Her angir vi at vi forventer at servicen vi kontakter har følgande sertifikat (f.eks. EVRY sitt)
                if (_channelFactory.Credentials == null)
                {
                    throw new Exception("_channelFactory.Credentials was null..");
                }

                //Her setter vi channelfactory sitt sertifikat til sertfikatet vi henta fra AP (f.eks. EVRY sitt):
                _channelFactory.Credentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(serviceMetadata.Certificate);

                //Slår på custom validator for sertifikatet fra eksternt aksesspunkt:
                _channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
                _channelFactory.Credentials.ServiceCertificate.Authentication.RevocationMode             = X509RevocationMode.NoCheck;
                _channelFactory.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = new CertificateValidator
                {
                    ExpectedCertificate = serviceMetadata.Certificate,
                    ExpectedIssuer      = CertificateIssuer.AccessPointCA,
                    RevocationMode      = X509RevocationMode.NoCheck
                };

                //2. set identity til SERVER. gjær nokon endringar på channelfactory sitt endpoint (createDnsIdentity basert på dns i sertifikat)
                var dnsName = serviceMetadata.Certificate.GetNameInfo(X509NameType.SimpleName, false);
                if (string.IsNullOrEmpty(dnsName))
                {
                    throw new Exception("Could not resolve dnsName for certificate..");
                }

                //Her endrer vi adressen til channelfactory til å gå mot gitt aksesspunkt:
                _channelFactory.Endpoint.Address = new EndpointAddress(_channelFactory.Endpoint.Address.Uri, EndpointIdentity.CreateDnsIdentity(dnsName), _channelFactory.Endpoint.Address.Headers);

                //set identity til CLIENT (oss), og create token:
                Log.Info("Creating token..");
                var thisUrl = serviceMetadata.Address; //_channelFactory.Endpoint.Address.Uri;
                X509Certificate2   clientCertificate = _channelFactory.Credentials.ClientCertificate.Certificate;
                ClaimsIdentity     myOwnClaims       = AccessPointToken.MakeClaims(createRequest.SenderIdentifier.Value, AssuranceLevel);
                Saml2SecurityToken token             = AccessPointToken.ClaimsToSaml2SenderVouchesToken(myOwnClaims, thisUrl.AbsoluteUri, clientCertificate);

                //åpner proxy:
                Log.Info("Creating proxy on channelFactory with issuedToken...");
                var proxy = _channelFactory.CreateChannelWithIssuedToken(token, new EndpointAddress(thisUrl, _channelFactory.Endpoint.Address.Identity));
                Log.Info("Proxy created ok.");

                //kaller service:
                Log.Info("Calling service");
                var response = proxy.Create(createRequest);


                var sendResult = new SendResult()
                {
                    MessageId = createRequest.MessageIdentifier,
                    Response  = response,
                    TimeSpent = DateTime.Now.Subtract(start)
                };

                Log.InfoFormat("response OK. Message {0} sent OK!", sendResult.MessageId);
                return(sendResult);
            }
            catch (Exception exception)
            {
                Log.Error("Error when sending invoice..");
                Log.Error(exception);
                throw;
            }
        }