Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StsService"/> class.
        /// </summary>
        public StsService()
        {
            WindowsSecurityTokenServiceConfiguration config = new WindowsSecurityTokenServiceConfiguration();

            config.TrustEndpoints.Add(new ServiceHostEndpointConfiguration(typeof(IWSTrust13AsyncContract), new WS2007HttpBinding(), ConfigurationManager.AppSettings["IssuerName"]));

            Task.Factory.StartNew(() =>
            {
                try
                {
                    WSTrustServiceHost host = new WSTrustServiceHost(config);
                    host.Opened            += HostOpened;
                    host.Faulted           += HostFaulted;
                    host.Closed            += HostClosed;
                    host.Open();
                    Console.WriteLine(@"Local STS started on port : {0}", ConfigurationManager.AppSettings["IssuerName"]);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(
                        @"Error there is a isue with the host({0} : {1} ",
                        ConfigurationManager.AppSettings["IssuerName"],
                        ex);
                }
            });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a System.ServiceModel.ServiceHost for a specified type of service with a specific base address.
        /// </summary>
        /// <param name="serviceType">Specifies the type of service to host.</param>
        /// <param name="baseAddresses">The System.Array of type System.Uri that contains the base addresses for the service hosted.</param>
        /// <returns></returns>
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            IServiceProvider sp   = DI.DefaultServiceProvider;
            Type             stsc = typeof(SecurityTokenServiceConfiguration);

            if (stsc.IsAssignableFrom(serviceType))
            {
                // try resolving concrete or base STS configuration first to enable DI for it
                SecurityTokenServiceConfiguration stsConfig = sp.GetService(serviceType) as SecurityTokenServiceConfiguration;
                if (stsConfig == null)
                {
                    stsConfig = sp.GetService(stsc) as SecurityTokenServiceConfiguration;
                }
                if (stsConfig == null)
                {
                    stsConfig = Activator.CreateInstance(serviceType) as SecurityTokenServiceConfiguration;
                }
                ServiceHost host = new WSTrustServiceHost(stsConfig, baseAddresses);
                if (stsConfig.ServiceCertificate != null)
                {
                    host.Credentials.ServiceCertificate.Certificate = stsConfig.ServiceCertificate;
                }
                return(host);
            }
            return(new ServiceProviderHost(sp, serviceType, baseAddresses));
        }
    /// <summary>
    /// Creates a ServiceHost instance. To register a Security Token Service in IIS create 
    /// a .svc file in the following format.
    /// &lt;%@ServiceHost  language=c# Debug="true" Factory="UserNameCardStsHostFactory" Service="&lt;CustomSecurityTokenServiceConfiguration>" %>
    /// </summary>
    /// <param name="constructorString">The STSConfiguration name that is passed to the Service argument in the .svc file.</param>
    /// <param name="baseAddresses">The address under which the .svc file is registered.</param>
    /// <returns>Instance of Service Host.</returns>
    /// <exception cref="ArgumentNullException">One of the input arguments is either null or is an empty string.</exception>
    /// <exception cref="InvalidOperationException">The 'constructorString' parameter does not refer to a type 'SecurityTokenServiceConfiguration'.</exception>
    public override ServiceHostBase CreateServiceHost( string constructorString, Uri[] baseAddresses )
    {
        if ( String.IsNullOrEmpty( constructorString ) )
        {
            throw new ArgumentNullException( "constructorString" );
        }

        if ( baseAddresses == null )
        {
            throw new ArgumentNullException( "baseAddresses" );
        }

        SecurityTokenServiceConfiguration securityTokenServiceConfiguration = CreateSecurityTokenServiceConfiguration( constructorString );
        if ( securityTokenServiceConfiguration == null )
        {
            throw new InvalidOperationException( "CreateSecurityTokenServiceConfiguration return a null SecurityTokenServiceConfiguration object" );
        }

        WSTrustServiceHost serviceHost =  new WSTrustServiceHost( securityTokenServiceConfiguration, baseAddresses );
        
        //
        // Configure an EndpointIdentity for the service host.
        // If no EndpointIdentity is required, you may wish to set the SecurityTokenServiceConfiguration.TrustEndpoints property instead.
        //
        serviceHost.Description.Endpoints.Add( new ServiceEndpoint( 
            ContractDescription.GetContract( typeof( IWSTrust13SyncContract ) ),
                                             new UserNameWSTrustBinding( SecurityMode.TransportWithMessageCredential ),
                                             new EndpointAddress( new Uri( StsAddress ), EndpointIdentity.CreateX509CertificateIdentity( SslCert ) ) ) );

        serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>().HttpsGetUrl = new Uri( StsMexAddress );

        return serviceHost;
    }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            // Create and setup the configuration for our STS
            SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration("STS");

            // Add the STS endpoint information
            config.TrustEndpoints.Add(
                new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetSTSBinding(), "http://localhost:6000/STS"));

            // Set the STS implementation class type
            config.SecurityTokenService = typeof(CustomSecurityTokenService);
            SecurityTokenHandlerCollection actAsHandlerCollection = config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.ActAs];

            actAsHandlerCollection.Configuration.IssuerNameRegistry = new ActAsIssuerNameRegistry();
            // The token that we receive in the <RequestSecurityToken><ActAs> element was issued to the service proxies.
            // By adding the proxy audience URIs here we are enforcing the implicit contract that the STS will accept
            // only tokens issued to the proxy as an ActAs token.
            actAsHandlerCollection.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://localhost/WFE/default.aspx"));
            actAsHandlerCollection.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://localhost/Service1/Service1.svc"));

            // Create the WS-Trust service host with our STS configuration
            using (WSTrustServiceHost host = new WSTrustServiceHost(config, new Uri("http://localhost:6000/STS")))
            {
                host.Open();

                Console.WriteLine("STS started, press ENTER to stop ...");
                Console.ReadLine();

                host.Close();
            }
        }
        static void Main(string[] args)
        {
            SigningCredentials signingCreds = new X509SigningCredentials("CN=MySTS".ToCertificate());

            SecurityTokenServiceConfiguration config =
                new SecurityTokenServiceConfiguration("http://MySTS", signingCreds);

            config.SecurityTokenHandlers.AddOrReplace(new CustomUsernameTokenHandler());
            config.SecurityTokenService = typeof(MySecurityTokenService);

            // Create the WS-Trust service host with our STS configuration
            var host = new WSTrustServiceHost(config, new Uri("http://localhost:6000/MySTS"));

            try
            {
                host.Open();
                Console.WriteLine("STS is ready to issue tokens… Press ENTER to shutdown");
                Console.ReadLine();
                host.Close();
            }
            finally
            {
                if (host.State != CommunicationState.Faulted)
                {
                    host.Close();
                }
                else
                {
                    host.Abort();
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StsService"/> class.
        /// </summary>
        public StsService()
        {
            WindowsSecurityTokenServiceConfiguration config = new WindowsSecurityTokenServiceConfiguration();
            config.TrustEndpoints.Add(new ServiceHostEndpointConfiguration(typeof(IWSTrust13AsyncContract), new WS2007HttpBinding(), ConfigurationManager.AppSettings["IssuerName"]));

            Task.Factory.StartNew(() =>
                {
                    try
                    {
                        WSTrustServiceHost host = new WSTrustServiceHost(config);
                        host.Opened += HostOpened;
                        host.Faulted += HostFaulted;
                        host.Closed += HostClosed;
                        host.Open();
                        Console.WriteLine(@"Local STS started on port : {0}", ConfigurationManager.AppSettings["IssuerName"]);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(
                            @"Error there is a isue with the host({0} : {1} ",
                            ConfigurationManager.AppSettings["IssuerName"],
                            ex);
                    }
                });
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates and configures a <see cref="WSTrustServiceHost"/> with a specific base address.
        /// </summary>
        /// <param name="serviceType">Specifies the type of service to host (ignored).</param>
        /// <param name="baseAddresses">The <see cref="T:Uri"/> array that contains the base addresses for the service.</param>
        /// <returns>A <see cref="WSTrustServiceHost"/> with a specific base address.</returns>
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var config          = new SOFASecurityTokenServiceConfiguration();
            var host            = new WSTrustServiceHost(config, baseAddresses);
            var serviceBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            serviceBehavior.AddressFilterMode = AddressFilterMode.Any;
            return(host);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Creates and configures a <see cref="WSTrustServiceHost"/> with a specific base address.
        /// </summary>
        /// <param name="constructorString">The constructor string (ignored).</param>
        /// <param name="baseAddresses">The <see cref="T:Uri"/> array that contains the base addresses for the service.</param>
        /// <returns></returns>
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            var config          = new SOFASecurityTokenServiceConfiguration();
            var host            = new WSTrustServiceHost(config, baseAddresses);
            var serviceBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            serviceBehavior.AddressFilterMode = AddressFilterMode.Any;
            return(host);
        }
Ejemplo n.º 9
0
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            string issuerName = WebConfigurationManager.AppSettings[Common.IssuerName];
            string signingCertificateThumprint = WebConfigurationManager.AppSettings[Common.SigningCertificateThumbprint];
            string issuerCertificateThumprint  = WebConfigurationManager.AppSettings[Common.IssuerCertificateThumprint];
            var    config = new STSConfiguration(issuerName, signingCertificateThumprint, issuerCertificateThumprint);

            Uri baseUri = baseAddresses.FirstOrDefault(a => a.Scheme == Uri.UriSchemeHttps);

            if (baseUri == null)
            {
                throw new InvalidOperationException("The STS should be hosted under https.");
            }

            WSTrustServiceHost host = new WSTrustServiceHost(config, baseAddresses);

            host.AddServiceEndpoint(typeof(IWSTrust13SyncContract), STSBinding, baseUri.AbsoluteUri);
            return(host);
        }
Ejemplo n.º 10
0
        private static WSTrustServiceHost CreateSecurityTokenServiceHost()
        {
            var signingCredentials = new X509SigningCredentials(STSCertificate);
            var stsConfig          = new SecurityTokenServiceConfiguration(STSAddress, signingCredentials);

            stsConfig.SecurityTokenService = typeof(CustomSecurityTokenService);

            // Add the STS endpoint information
            stsConfig.TrustEndpoints.Add(
                new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetSecurityTokenServiceBinding(), STSAddress));

            // Setting the certificate will automatically populate the token resolver
            // that is used to decrypt the client entropy in the RST.
            stsConfig.ServiceCertificate = STSCertificate;

            WSTrustServiceHost stsHost = new WSTrustServiceHost(stsConfig, new Uri(STSAddress));

            return(stsHost);
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            SecurityTokenServiceConfiguration config = new PetShopSTSConfiguration();

            using (WSTrustServiceHost host = new WSTrustServiceHost(config))
            {
#if DEBUG
                Console.WriteLine("Including exception details in faults");
                var serviceDebugBehavior = host.Description.Behaviors.Find <ServiceDebugBehavior>();
                serviceDebugBehavior.IncludeExceptionDetailInFaults = true;
#endif

                host.Open();

                Console.Title = host.Description.Endpoints[0].Address.Uri.ToString();
                Console.WriteLine("PetShopSTS started, press ENTER to stop ...");
                Console.ReadLine();
            }
        }
    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
    {
        StreamWriter file = new StreamWriter("c:\\temp\\IdentityProviderSts.OnBehalfOfSecurityTokenServiceFactory - CreateServiceHost.txt", true);
        file.WriteLine("_________________________________________");
        file.WriteLine("DateTime: " + DateTime.Now.ToString());

        file.WriteLine("constructorString:" + constructorString);
        file.Close();


        SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration("https://ha50idp:8544/IDP-STS/Issue.svc");

        //Uri baseUri = baseAddresses.FirstOrDefault(a => a.Scheme == "https");
        //if (baseUri == null)
        //    throw new InvalidOperationException("The STS should be hosted under https");

        //config.TrustEndpoints.Add(new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetCertificateCredentialsBinding(), baseUri + ""));
        
        // Set the STS implementation class type
        config.SecurityTokenService = typeof(CustomSecurityTokenService);

        // Create a security token handler collection and then provide with a SAML11 security token
        // handler and set the Audience restriction to Never
        SecurityTokenHandlerCollection onBehalfOfHandlers = new SecurityTokenHandlerCollection();
        Saml2SecurityTokenHandler onBehalfOfTokenHandler = new Saml2SecurityTokenHandler();
        
        onBehalfOfHandlers.Add(onBehalfOfTokenHandler);
        //onBehalfOfHandlers.Add(userNameTokenHandler);
        onBehalfOfHandlers.Configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;

        // Set the appropriate issuer name registry
        //onBehalfOfHandlers.Configuration.IssuerNameRegistry = new IdentityProviderIssuerNameRegistry();

        // Set the token handlers collection
        config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.OnBehalfOf] = onBehalfOfHandlers;

//        WindowsUserNameSecurityTokenHandler userNameTokenHandler = new WindowsUserNameSecurityTokenHandler();
//        config.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.Default].Add(userNameTokenHandler);
        
        WSTrustServiceHost host = new WSTrustServiceHost(config, baseAddresses);        
        return host;
    }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            WSTrustServiceHost stsHost = null;

            try
            {
                SecurityTokenServiceConfiguration stsConfiguration = new SecurityTokenServiceConfiguration(Address.StsAddress,
                                                                                                           new X509SigningCredentials(
                                                                                                               CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine,
                                                                                                                                              "CN=localhost")));
                stsConfiguration.SecurityTokenService = typeof(CustomSecurityTokenService);

                // Add the STS endpoint information
                stsConfiguration.TrustEndpoints.Add(
                    new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), new WindowsWSTrustBinding(), Address.StsAddress));

                stsHost = new WSTrustServiceHost(stsConfiguration, new Uri(Address.StsAddress));
                stsHost.Open();

                Console.WriteLine("The security token service has started at {0}.\n", Address.StsAddress);
                Console.WriteLine("Press [Enter] to stop.\n");
                Console.ReadLine();
            }
            finally
            {
                try
                {
                    if (stsHost != null)
                    {
                        stsHost.Close();
                    }
                }
                catch (CommunicationException)
                {
                }
                catch (TimeoutException)
                {
                }
            }
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            // Create and setup the configuration for our STS
            SigningCredentials signingCreds          = new X509SigningCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateName));
            SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration("http://SecurityTokenService", signingCreds);

            // Add the STS endoint information
            config.TrustEndpoints.Add(
                new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), new WindowsWSTrustBinding(), "http://localhost:6000/SecurityTokenService"));

            // Set the STS implementation class type
            config.SecurityTokenService = typeof(MySecurityTokenService);

            // Create the WS-Trust service host with our STS configuration
            using (WSTrustServiceHost host = new WSTrustServiceHost(config, new Uri("http://localhost:6000/SecurityTokenService")))
            {
                host.Open();
                Console.WriteLine("SecurityTokenService started, press ENTER to stop ...");
                Console.ReadLine();
                host.Close();
            }
        }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            var config = CreateSecurityTokenServiceConfiguration(constructorString);
            var host = new WSTrustServiceHost(config, baseAddresses);

            // add behavior for load balancing support
            host.Description.Behaviors.Add(new UseRequestHeadersForMetadataAddressBehavior());

            // modify address filter mode for load balancing
            var serviceBehavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
            serviceBehavior.AddressFilterMode = AddressFilterMode.Any;

            var credential = new ServiceCredentials();
            credential.ServiceCertificate.Certificate = Configuration.TokenSigningCertificate;
            host.Description.Behaviors.Add(credential);

            host.AddServiceEndpoint(
                typeof(IWSTrust13SyncContract),
                new WindowsWSTrustBinding(SecurityMode.Message),
                "/Message/Windows");

            return host;
        }
        /// <summary>
        /// Creates a service host to process WS-Trust 1.3 requests
        /// </summary>
        /// <param name="constructorString">The constructor string.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <returns>A WS-Trust ServiceHost</returns>
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            var globalConfiguration = ConfigurationRepository.Configuration;
            var config = CreateSecurityTokenServiceConfiguration(constructorString);
            var host = new WSTrustServiceHost(config, baseAddresses);
            
            // add behavior for load balancing support
            host.Description.Behaviors.Add(new UseRequestHeadersForMetadataAddressBehavior());

            // modify address filter mode for load balancing
            var serviceBehavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
            serviceBehavior.AddressFilterMode = AddressFilterMode.Any;

            // add and configure a mixed mode security endpoint
            if (ConfigurationRepository.Endpoints.WSTrustMixed)
            {
                EndpointIdentity epi = null;
                if (ConfigurationRepository.Configuration.EnableStrongEpiForSsl)
                {
                    if (ConfigurationRepository.SslCertificate.Certificate == null)
                    {
                        throw new ServiceActivationException("No SSL certificate configured for strong endpoint identity.");
                    }

                    epi = EndpointIdentity.CreateX509CertificateIdentity(ConfigurationRepository.SslCertificate.Certificate);
                }

                if (globalConfiguration.EnableClientCertificates)
                {
                    var sep2 = host.AddServiceEndpoint(
                        typeof(IWSTrust13SyncContract),
                        new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                        Endpoints.Paths.WSTrustMixedCertificate);

                    if (epi != null)
                    {
                        sep2.Address = new EndpointAddress(sep2.Address.Uri, epi);
                    }
                }

                var sep = host.AddServiceEndpoint(
                    typeof(IWSTrust13SyncContract),
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    Endpoints.Paths.WSTrustMixedUserName);

                if (epi != null)
                {
                    sep.Address = new EndpointAddress(sep.Address.Uri, epi);
                }
            }

            // add and configure a message security endpoint
            if (ConfigurationRepository.Endpoints.WSTrustMessage)
            {
                var credential = new ServiceCredentials();
                credential.ServiceCertificate.Certificate = ConfigurationRepository.SigningCertificate.Certificate;
                host.Description.Behaviors.Add(credential);

                if (globalConfiguration.EnableClientCertificates)
                {
                    host.AddServiceEndpoint(
                        typeof(IWSTrust13SyncContract),
                        new CertificateWSTrustBinding(SecurityMode.Message),
                        Endpoints.Paths.WSTrustMessageCertificate);
                }

                host.AddServiceEndpoint(
                    typeof(IWSTrust13SyncContract),
                    new UserNameWSTrustBinding(SecurityMode.Message),
                    Endpoints.Paths.WSTrustMessageUserName);
            }

            return host;
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            ServiceHost        serviceHost = null;
            WSTrustServiceHost securityTokenServiceHost = null;

            try
            {
                //
                // Open the calculator service host.
                //
                serviceHost = CreateServiceHost();
                serviceHost.Open();
                Console.WriteLine("Started the calculator service.");
                WriteEndpoints(serviceHost);

                //
                // Start the STS
                //
                securityTokenServiceHost = CreateSecurityTokenServiceHost();
                securityTokenServiceHost.Open();
                Console.WriteLine("Started the STS.");
                WriteEndpoints(securityTokenServiceHost);

                //
                // Call the service and let the framework request the
                // token from the STS automatically.
                //
                Console.WriteLine("Calling the service with an issued token implicitly acquired using WCF...");
                CallService();

                //
                // Use the WSTrustChannel component to manually acquire
                // the issued token and use it to secure a request to
                // the web service.
                //
                Console.WriteLine("Calling the service with an issued token explicitly acquired using the WSTrustChannel...");
                CallServiceWithExplicitToken(GetIssuedToken());

                serviceHost.Close();
                serviceHost = null;

                securityTokenServiceHost.Close();
                securityTokenServiceHost = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("=== Unexpected exception caught ===");
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                if (serviceHost != null)
                {
                    serviceHost.Abort();
                }
                if (securityTokenServiceHost != null)
                {
                    securityTokenServiceHost.Abort();
                }
            }

            Console.WriteLine("Press <ENTER> to continue.");
            Console.ReadLine();
        }
        /// <summary>
        /// Creates a service host to process WS-Trust 1.3 requests
        /// </summary>
        /// <param name="constructorString">The constructor string.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <returns>A WS-Trust ServiceHost</returns>
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            var globalConfiguration = ConfigurationRepository.Global;
            var config = CreateSecurityTokenServiceConfiguration(constructorString);
            var host   = new WSTrustServiceHost(config, baseAddresses);

            // add behavior for load balancing support
            host.Description.Behaviors.Add(new UseRequestHeadersForMetadataAddressBehavior());

            // modify address filter mode for load balancing
            var serviceBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            serviceBehavior.AddressFilterMode = AddressFilterMode.Any;

            // add and configure a mixed mode security endpoint
            if (ConfigurationRepository.WSTrust.Enabled &&
                ConfigurationRepository.WSTrust.EnableMixedModeSecurity &&
                !ConfigurationRepository.Global.DisableSSL)
            {
                EndpointIdentity epi = null;

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    var sep2 = host.AddServiceEndpoint(
                        typeof(IWSTrust13SyncContract),
                        new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                        Endpoints.Paths.WSTrustMixedCertificate);

                    if (epi != null)
                    {
                        sep2.Address = new EndpointAddress(sep2.Address.Uri, epi);
                    }
                }

                var sep = host.AddServiceEndpoint(
                    typeof(IWSTrust13SyncContract),
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    Endpoints.Paths.WSTrustMixedUserName);

                if (epi != null)
                {
                    sep.Address = new EndpointAddress(sep.Address.Uri, epi);
                }
            }

            // add and configure a message security endpoint
            if (ConfigurationRepository.WSTrust.Enabled && ConfigurationRepository.WSTrust.EnableMessageSecurity)
            {
                var credential = new ServiceCredentials();
                credential.ServiceCertificate.Certificate = ConfigurationRepository.Keys.SigningCertificate;
                host.Description.Behaviors.Add(credential);

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    host.AddServiceEndpoint(
                        typeof(IWSTrust13SyncContract),
                        new CertificateWSTrustBinding(SecurityMode.Message),
                        Endpoints.Paths.WSTrustMessageCertificate);
                }

                host.AddServiceEndpoint(
                    typeof(IWSTrust13SyncContract),
                    new UserNameWSTrustBinding(SecurityMode.Message),
                    Endpoints.Paths.WSTrustMessageUserName);
            }

            ServiceMetadataBehavior metad = host.Description.Behaviors.Find <ServiceMetadataBehavior>();

            if (metad == null)
            {
                metad = new ServiceMetadataBehavior();
            }
            for (int i = 0; i < baseAddresses.Length; i++)
            {
                // there will be two bindings: one for http and one secure
                switch (baseAddresses[i].Scheme)
                {
                case "http":
                    metad.HttpGetEnabled = true;
                    metad.HttpGetUrl     = new Uri(baseAddresses[i], "/issue/wstrust/mex");
                    break;

                case "https":
                    metad.HttpsGetEnabled = true;
                    metad.HttpsGetUrl     = new Uri(baseAddresses[i], "/issue/wstrust/mex");
                    break;
                }
            }

            return(host);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Creates a service host to process WS-Trust 1.3 requests
        /// </summary>
        /// <param name="constructorString">The constructor string.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <returns>A WS-Trust ServiceHost</returns>
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            var globalConfiguration = ConfigurationRepository.Global;
            var config = CreateSecurityTokenServiceConfiguration(constructorString);
            var host   = new WSTrustServiceHost(config, baseAddresses);

            // add behavior for load balancing support
            host.Description.Behaviors.Add(new UseRequestHeadersForMetadataAddressBehavior());

            // modify address filter mode for load balancing
            var serviceBehavior = host.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            serviceBehavior.AddressFilterMode = AddressFilterMode.Any;

            // add and configure a mixed mode security endpoint
            if (ConfigurationRepository.WSTrust.Enabled &&
                ConfigurationRepository.WSTrust.EnableMixedModeSecurity &&
                !ConfigurationRepository.Global.DisableSSL)
            {
                EndpointIdentity epi = null;

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    var sep2 = host.AddServiceEndpoint(
                        typeof(IWSTrust13SyncContract),
                        new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                        Endpoints.Paths.WSTrustMixedCertificate);

                    if (epi != null)
                    {
                        sep2.Address = new EndpointAddress(sep2.Address.Uri, epi);
                    }
                }

                var sep = host.AddServiceEndpoint(
                    typeof(IWSTrust13SyncContract),
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    Endpoints.Paths.WSTrustMixedUserName);

                if (epi != null)
                {
                    sep.Address = new EndpointAddress(sep.Address.Uri, epi);
                }
            }

            // add and configure a message security endpoint
            if (ConfigurationRepository.WSTrust.Enabled && ConfigurationRepository.WSTrust.EnableMessageSecurity)
            {
                var credential = new ServiceCredentials();
                credential.ServiceCertificate.Certificate = ConfigurationRepository.Keys.SigningCertificate;
                host.Description.Behaviors.Add(credential);

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    host.AddServiceEndpoint(
                        typeof(IWSTrust13SyncContract),
                        new CertificateWSTrustBinding(SecurityMode.Message),
                        Endpoints.Paths.WSTrustMessageCertificate);
                }

                host.AddServiceEndpoint(
                    typeof(IWSTrust13SyncContract),
                    new UserNameWSTrustBinding(SecurityMode.Message),
                    Endpoints.Paths.WSTrustMessageUserName);
            }

            return(host);
        }
Ejemplo n.º 20
0
        static void Main()
        {
            ServiceHost            serviceHost              = null;
            ChannelFactory <IEcho> echoChannelFactory       = null;
            WSTrustServiceHost     securityTokenServiceHost = null;

            try
            {
                //
                // Start the service
                //
                serviceHost = new ServiceHost(typeof(EchoService));
                string serviceAddress = "http://localhost:8080/EchoService";

                serviceHost.AddServiceEndpoint(typeof(IEcho), GetServiceBinding(), serviceAddress);
                ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl     = new Uri(serviceAddress);
                serviceHost.Description.Behaviors.Add(metadataBehavior);
                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), serviceAddress + "/mex");
                serviceHost.Credentials.ServiceCertificate.SetCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My);

                serviceHost.Open();
                Console.WriteLine("The echo service has started at {0}.\n", serviceAddress);

                //
                // Start the STS
                //
                SecurityTokenServiceConfiguration securityTokenServiceConfiguration = new SecurityTokenServiceConfiguration(securityTokenServiceAddress, new X509SigningCredentials(serviceHost.Credentials.ServiceCertificate.Certificate));
                securityTokenServiceConfiguration.WSTrust13RequestSerializer = new CustomWSTrust13RequestSerializer();
                securityTokenServiceConfiguration.SecurityTokenService       = typeof(CustomSecurityTokenService);

                // Add the STS endpoint information
                securityTokenServiceConfiguration.TrustEndpoints.Add(
                    new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetSecurityTokenServiceBinding(), securityTokenServiceAddress));

                securityTokenServiceHost = new WSTrustServiceHost(securityTokenServiceConfiguration, new Uri(securityTokenServiceAddress));
                securityTokenServiceHost.Open();

                Console.WriteLine("The security token service has started at {0}.\n", securityTokenServiceAddress);

                //
                // Invoke the client
                //
                echoChannelFactory = new ChannelFactory <IEcho>(GetClientBinding(), new EndpointAddress(new Uri(serviceAddress), EndpointIdentity.CreateDnsIdentity("localhost")));

                IEcho client = echoChannelFactory.CreateChannel();
                ((IClientChannel)client).OperationTimeout = TimeSpan.MaxValue;

                Console.WriteLine("The client sent a request to the STS to retrieve a SAML token and then sent the hello request to the echo service.\n");
                Console.WriteLine("The echo service finally returned '{0}'.\n", client.Echo("Hello"));

                Console.WriteLine("Press [Enter] to continue.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                try
                {
                    if (echoChannelFactory != null)
                    {
                        echoChannelFactory.Close();
                    }

                    if (serviceHost != null)
                    {
                        serviceHost.Close();
                    }

                    if (securityTokenServiceHost != null)
                    {
                        securityTokenServiceHost.Close();
                    }
                }
                catch (CommunicationException)
                {
                }
            }
        }
Ejemplo n.º 21
0
        static void Main()
        {
            ServiceHost            serviceHost        = null;
            ChannelFactory <IEcho> echoChannelFactory = null;
            WSTrustServiceHost     trustServiceHost   = null;

            try
            {
                CustomTokenHandler handler = new CustomTokenHandler();

                //
                // Start the service
                //
                serviceHost = new ServiceHost(typeof(EchoService));
                string serviceAddress = "http://" + Environment.MachineName + ":8080/EchoService";

                ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl     = new Uri(serviceAddress);
                serviceHost.Description.Behaviors.Add(metadataBehavior);
                serviceHost.AddServiceEndpoint(typeof(IEcho), GetServiceBinding(), serviceAddress);
                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), serviceAddress + "/mex");
                serviceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.Root, X509FindType.FindByThumbprint, thumbprint);

                FederatedServiceCredentials.ConfigureServiceHost(serviceHost);
                //
                // Update the service credentials so that it can deserialize the custom token
                //
                (( FederatedServiceCredentials )serviceHost.Credentials).SecurityTokenHandlers.Add(handler);
                serviceHost.Open();
                Console.WriteLine("The echo service has started at {0}.\n", serviceAddress);

                //
                // Start the SecurityTokenService
                //
                X509Certificate2   certificate = CertificateUtil.GetCertificate(StoreName.Root, StoreLocation.LocalMachine, thumbprint);
                SigningCredentials credentials = new X509SigningCredentials(certificate);
                SecurityTokenServiceConfiguration securityTokenServiceConfiguration = new SecurityTokenServiceConfiguration(securityTokenServiceAddress, credentials);
                securityTokenServiceConfiguration.SecurityTokenService = typeof(SampleTokenService);

                // register a handler to the SecurityTokenService here so that it can issue the custom token
                securityTokenServiceConfiguration.SecurityTokenHandlers.Add(handler);

                // Add the STS endpoint information
                securityTokenServiceConfiguration.TrustEndpoints.Add(
                    new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), GetSecurityTokenServiceBinding(), securityTokenServiceAddress));

                securityTokenServiceConfiguration.ServiceCertificate = certificate;

                trustServiceHost = new WSTrustServiceHost(securityTokenServiceConfiguration, new Uri(securityTokenServiceAddress));
                trustServiceHost.Open();
                Console.WriteLine("The security token service has started at {0}.\n", securityTokenServiceAddress);

                //
                // Invoke the client
                //



                echoChannelFactory = new ChannelFactory <IEcho>(GetClientBinding(),
                                                                new EndpointAddress(new Uri(serviceAddress),
                                                                                    EndpointIdentity.CreateDnsIdentity("localhost")));

                IEcho client = echoChannelFactory.CreateChannel();
                ((IClientChannel)client).OperationTimeout = TimeSpan.MaxValue;


                string echoedString = client.Echo("Hello");
                Console.WriteLine("The echo service returns '{0}'. \n", echoedString);


                Console.WriteLine("Press [Enter] to close service.");
                Console.ReadLine();

                echoChannelFactory.Close();

                Console.WriteLine("Press [Enter] to continue.");
                Console.ReadLine();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);
                if (echoChannelFactory != null)
                {
                    echoChannelFactory.Abort();
                }
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);
                if (echoChannelFactory != null)
                {
                    echoChannelFactory.Abort();
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.InnerException.Message);
            }
            finally
            {
                if (serviceHost != null && serviceHost.State != CommunicationState.Faulted)
                {
                    serviceHost.Close();
                }

                if (trustServiceHost != null && trustServiceHost.State != CommunicationState.Faulted)
                {
                    trustServiceHost.Close();
                }
            }
        }