Beispiel #1
0
    public static void Main()
    {
        ServiceHost   host    = new ServiceHost(typeof(Foo));
        WSHttpBinding binding = new WSHttpBinding();

        //binding.Security.Message.EstablishSecurityContext = false;
        binding.Security.Message.NegotiateServiceCredential = false;
        binding.Security.Message.ClientCredentialType       =
            MessageCredentialType.IssuedToken;
        binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
        host.AddServiceEndpoint("IFoo",
                                binding, new Uri("http://localhost:8080"));
        ServiceCredentials cred = new ServiceCredentials();

        cred.ServiceCertificate.Certificate =
            new X509Certificate2("test.pfx", "mono");
        cred.IssuedTokenAuthentication.AllowUntrustedRsaIssuers  = true;
        cred.IssuedTokenAuthentication.CertificateValidationMode =
            X509CertificateValidationMode.None;
        host.Description.Behaviors.Add(cred);
        host.Description.Behaviors.Find <ServiceDebugBehavior> ()
        .IncludeExceptionDetailInFaults = true;
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

        smb.HttpGetEnabled = true;
        smb.HttpGetUrl     = new Uri("http://localhost:8080/wsdl");
        host.Description.Behaviors.Add(smb);
        host.Open();
        Console.WriteLine("Hit [CR] key to close ...");
        Console.ReadLine();
        host.Close();
    }
Beispiel #2
0
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.ProtectionTokenParameters =
			new SslSecurityTokenParameters ();
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.SecureConversationAuthentication.SecurityStateEncoder =
			new MyEncoder ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
//		foreach (ServiceEndpoint se in host.Description.Endpoints)
//			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #3
0
        protected override bool Unbind(ServiceCredentials credentials)
        {
            if (credentials == null)
            {
                return(false);
            }

            Logger.Debug(Strings.SqlNodeUnbindServiceDebugMessage, credentials.SerializeToJson());

            string user         = credentials.User;
            string databaseName = credentials.Name;

            using (SqlConnection databaseConnection = new SqlConnection(this.ConnectionString))
            {
                databaseConnection.Open();
                databaseConnection.ChangeDatabase(databaseName);

                using (SqlCommand cmdUserExists = new SqlCommand(string.Format(CultureInfo.InvariantCulture, "select count(*) from sys.sysusers where name=N'{0}'", user), databaseConnection))
                {
                    int userCount = (int)cmdUserExists.ExecuteScalar();
                    if (userCount != 1)
                    {
                        throw new MSSqlErrorException(MSSqlErrorException.MSSqlCredentialsNotFound, user);
                    }
                }
            }

            this.DeleteDatabaseUser(user);
            return(true);
        }
        public static SslStreamSecurityUpgradeProvider CreateServerProvider(
            SslStreamSecurityBindingElement bindingElement, BindingContext context)
        {
            SecurityCredentialsManager credentialProvider =
                context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                credentialProvider = ServiceCredentials.CreateDefaultCredentials();
            }

            Uri listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            SecurityTokenManager tokenManager = credentialProvider.CreateSecurityTokenManager();

            RecipientServiceModelSecurityTokenRequirement serverCertRequirement = new RecipientServiceModelSecurityTokenRequirement();

            serverCertRequirement.TokenType = SecurityTokenTypes.X509Certificate;
            serverCertRequirement.RequireCryptographicToken = true;
            serverCertRequirement.KeyUsage        = SecurityKeyUsage.Exchange;
            serverCertRequirement.TransportScheme = context.Binding.Scheme;
            serverCertRequirement.ListenUri       = listenUri;

            SecurityTokenProvider tokenProvider = tokenManager.CreateSecurityTokenProvider(serverCertRequirement);

            if (tokenProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCredentialsUnableToCreateLocalTokenProvider, serverCertRequirement)));
            }

            SecurityTokenAuthenticator certificateAuthenticator =
                TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme, listenUri);

            return(new SslStreamSecurityUpgradeProvider(context.Binding, tokenProvider, bindingElement.RequireClientCertificate,
                                                        certificateAuthenticator, context.Binding.Scheme, bindingElement.IdentityVerifier, bindingElement.SslProtocols));
        }
        BuildChannelListenerCore <TChannel> (
            BindingContext context)
        {
            if (InitiatorTokenParameters == null)
            {
                throw new InvalidOperationException("InitiatorTokenParameters must be set before building channel factory.");
            }
            if (RecipientTokenParameters == null)
            {
                throw new InvalidOperationException("RecipientTokenParameters must be set before building channel factory.");
            }

            SetIssuerBindingContextIfRequired(InitiatorTokenParameters, context);
            SetIssuerBindingContextIfRequired(RecipientTokenParameters, context);

            ServiceCredentials cred = context.BindingParameters.Find <ServiceCredentials> ();

            if (cred == null)
            {
                // it happens when there is no ChannelFactory<T>.
                cred = new ServiceCredentials();
            }
            ServiceCredentialsSecurityTokenManager manager      = (ServiceCredentialsSecurityTokenManager)cred.CreateSecurityTokenManager();
            ChannelProtectionRequirements          requirements =
                context.BindingParameters.Find <ChannelProtectionRequirements> ();

            return(new SecurityChannelListener <TChannel> (
                       context.BuildInnerChannelListener <TChannel> (), new RecipientMessageSecurityBindingSupport(GetCapabilities(), manager, requirements)));
        }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the DuplexFrontEnd class
        /// </summary>
        /// <param name="listenUri">uri the frontend listen to</param>
        /// <param name="binding">binding that the frontend uses</param>
        /// <param name="observer">indicating the broker observer</param>
        /// <param name="clientManager">indicating the client manager</param>
        /// <param name="brokerAuth">indicating the broker authorization</param>
        /// <param name="sharedData">indicating the shared data</param>
        public DuplexFrontEnd(Uri listenUri, Binding binding, BrokerObserver observer, BrokerClientManager clientManager, BrokerAuthorization brokerAuth, SharedData sharedData)
            : base(listenUri.AbsoluteUri, observer, clientManager, brokerAuth, sharedData)
        {
            this.binding = binding;
            if (sharedData.StartInfo.UseAad)
            {
                BindingParameterCollection bindingParms = new BindingParameterCollection();
                var serviceCred = new ServiceCredentials();
                serviceCred.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, new NonHARegistry().GetSSLThumbprint().GetAwaiter().GetResult());

                bindingParms.Add(serviceCred);

                this.listener = binding.BuildChannelListener <IDuplexSessionChannel>(listenUri, bindingParms);
            }
            else if (sharedData.StartInfo.LocalUser.GetValueOrDefault())
            {
                this.listener = binding.BuildChannelListener <IDuplexSessionChannel>(listenUri, new ServiceCredentials().UseInternalAuthenticationAsync(true).GetAwaiter().GetResult());
            }
            else
            {
                this.listener = binding.BuildChannelListener <IDuplexSessionChannel>(listenUri);
            }

            this.acceptChannel  = new BasicCallbackReferencedThreadHelper <IAsyncResult>(this.AcceptChannel, this).CallbackRoot;
            this.receiveRequest = new BasicCallbackReferencedThreadHelper <IAsyncResult>(this.ReceiveRequest, this).CallbackRoot;
        }
        private void InitializeSecurityTokenAuthenticator()
        {
            ServiceCredentials credentialProvider = this.credentialProvider as ServiceCredentials;

            if (credentialProvider != null)
            {
                this.extractGroupsForWindowsAccounts = (this.AuthenticationScheme == AuthenticationSchemes.Basic) ? credentialProvider.UserNameAuthentication.IncludeWindowsGroups : credentialProvider.WindowsAuthentication.IncludeWindowsGroups;
                if (credentialProvider.UserNameAuthentication.UserNamePasswordValidationMode == UserNamePasswordValidationMode.Custom)
                {
                    this.userNameTokenAuthenticator = new CustomUserNameSecurityTokenAuthenticator(credentialProvider.UserNameAuthentication.GetUserNamePasswordValidator());
                }
                else if (credentialProvider.UserNameAuthentication.CacheLogonTokens)
                {
                    this.userNameTokenAuthenticator = new WindowsUserNameCachingSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts, credentialProvider.UserNameAuthentication.MaxCachedLogonTokens, credentialProvider.UserNameAuthentication.CachedLogonTokenLifetime);
                }
                else
                {
                    this.userNameTokenAuthenticator = new WindowsUserNameSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts);
                }
            }
            else
            {
                this.extractGroupsForWindowsAccounts = true;
                this.userNameTokenAuthenticator      = new WindowsUserNameSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts);
            }
            this.windowsTokenAuthenticator = new WindowsSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts);
        }
        public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
                                                    BindingContext context, bool isClient)
            : base(context.Binding)
        {
            this.extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            this.protectionLevel = bindingElement.ProtectionLevel;
            this.scheme          = context.Binding.Scheme;
            this.isClient        = isClient;
            this.listenUri       = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);

            SecurityCredentialsManager credentialProvider = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                if (isClient)
                {
                    credentialProvider = ClientCredentials.CreateDefaultCredentials();
                }
                else
                {
                    credentialProvider = ServiceCredentials.CreateDefaultCredentials();
                }
            }


            this.securityTokenManager = credentialProvider.CreateSecurityTokenManager();
        }
Beispiel #9
0
        public void HttpSelfHostConfiguration_UserNamePasswordValidator_PropagatesToBinding(
            string address,
            HttpBindingSecurityMode mode
            )
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            UserNamePasswordValidator validator = new Mock <UserNamePasswordValidator>().Object;
            HttpSelfHostConfiguration config    = new HttpSelfHostConfiguration(address)
            {
                UserNamePasswordValidator = validator
            };

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);

            // Assert
            Assert.NotNull(parameters);
            ServiceCredentials serviceCredentials = parameters.Find <ServiceCredentials>();

            Assert.NotNull(serviceCredentials);
            Assert.Equal(
                HttpClientCredentialType.Basic,
                binding.Security.Transport.ClientCredentialType
                );
            Assert.Equal(mode, binding.Security.Mode);
        }
    public static void Main()
    {
        var baseAddress = new Uri("https://localhost:8080/SelfHostedUsernamePasswordService");

        using (var host = new ServiceHost(typeof(SelfHostedUsernamePasswordService), baseAddress))
        {
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
            binding.Security.Message.ClientCredentialType   = BasicHttpMessageCredentialType.UserName;
            var endpoint = host.AddServiceEndpoint(typeof(ISelfHostedUsernamePasswordService), binding, baseAddress);
            var cf       = new ChannelFactory <ISelfHostedUsernamePasswordService>(binding, endpoint.Address);
            cf.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.LocalMachine,
                StoreName.My,
                X509FindType.FindByThumbprint,
                "0000000000000000000000000000000000000000");
            var credentialBehavior = new ServiceCredentials();
            credentialBehavior.UserNameAuthentication.CustomUserNamePasswordValidator = new UsernamePasswordValidator();
            credentialBehavior.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
            credentialBehavior.IssuedTokenAuthentication.AllowUntrustedRsaIssuers     = true;
            host.Description.Behaviors.Add(credentialBehavior);
            var metadataBehavior = new ServiceMetadataBehavior();
            metadataBehavior.HttpsGetEnabled = true;
            metadataBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(metadataBehavior);
            host.Open();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
            host.Close();
        }
    }
        /// <summary>
        /// 授权方法添加
        /// </summary>
        /// <param name="description"></param>
        private void AddAuthorizateBehaviors(ServiceDescription description)
        {
            var serviceCredentials = description.Behaviors.Find <ServiceCredentials>();

            if (serviceCredentials == null)
            {
                serviceCredentials = new ServiceCredentials();
                description.Behaviors.Add(serviceCredentials);
            }
            serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
            serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new UserNamePasswordCustomValidator(_authorizationService);

            /*
             * //使用测试实现安全验证
             * var serviceAuthorization = description.Behaviors.Find<ServiceAuthorizationBehavior>();
             * if (serviceAuthorization == null)
             * {
             *  serviceAuthorization = new ServiceAuthorizationBehavior();
             *  description.Behaviors.Add(serviceAuthorization);
             * }
             * serviceAuthorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
             * serviceAuthorization.ServiceAuthorizationManager = new AuthorizationManager();
             * //添加策略
             */
        }
Beispiel #12
0
        /// <summary>
        /// Override of the base class method. Substitues WCF IAuthorizationPolicy with
        /// <see cref="System.IdentityModel.Tokens.AuthorizationPolicy"/>.
        /// </summary>
        /// <param name="operationContext">Current OperationContext that contains all the IAuthorizationPolicies.</param>
        /// <returns>Read-Only collection of <see cref="IAuthorizationPolicy"/> </returns>
        protected override ReadOnlyCollection <IAuthorizationPolicy> GetAuthorizationPolicies(OperationContext operationContext)
        {
            //
            // Make sure we always return at least one claims identity, if there are no auth policies
            // that contain any identities, then return an anonymous identity wrapped in an authorization policy.
            //
            // If we do not, then Thread.CurrentPrincipal may end up being null inside service operations after the
            // authorization polices are evaluated since ServiceCredentials.ConfigureServiceHost will
            // turn the PrincipalPermissionMode knob to Custom.
            //

            ReadOnlyCollection <IAuthorizationPolicy> baseAuthorizationPolicies = base.GetAuthorizationPolicies(operationContext);

            if (baseAuthorizationPolicies == null)
            {
                return(AnonymousAuthorizationPolicy);
            }
            else
            {
                ServiceCredentials  sc = GetServiceCredentials();
                AuthorizationPolicy transformedPolicy = TransformAuthorizationPolicies(baseAuthorizationPolicies,
                                                                                       sc.IdentityConfiguration.SecurityTokenHandlers,
                                                                                       true);
                if (transformedPolicy == null || transformedPolicy.IdentityCollection.Count == 0)
                {
                    return(AnonymousAuthorizationPolicy);
                }
                return((new List <IAuthorizationPolicy>()
                {
                    transformedPolicy
                }).AsReadOnly());
            }
        }
Beispiel #13
0
    public static void Main()
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();

        sbe.ProtectionTokenParameters =
            new SspiSecurityTokenParameters();
        ServiceHost host = new ServiceHost(typeof(Foo));
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding binding = new CustomBinding(sbe, hbe);

        binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
        host.AddServiceEndpoint("IFoo",
                                binding, new Uri("http://localhost:8080"));
        ServiceCredentials cred = new ServiceCredentials();

        cred.SecureConversationAuthentication.SecurityStateEncoder =
            new MyEncoder();

        host.Description.Behaviors.Add(cred);
        host.Description.Behaviors.Find <ServiceDebugBehavior> ()
        .IncludeExceptionDetailInFaults = true;

/*
 *              ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
 *              smb.HttpGetEnabled = true;
 *              smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
 *              host.Description.Behaviors.Add (smb);
 */
        host.Open();
        Console.WriteLine("Hit [CR] key to close ...");
        Console.ReadLine();
        host.Close();
    }
Beispiel #14
0
	public static void Main ()
	{
		ServiceHost host = new ServiceHost (typeof (Foo));
		WSHttpBinding binding = new WSHttpBinding ();
		binding.Security.Message.EstablishSecurityContext = false;
		binding.Security.Message.NegotiateServiceCredential = false;
		binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		foreach (ServiceEndpoint se in host.Description.Endpoints)
			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #15
0
 protected override void OnOpened()
 {
     if (this.Description != null)
     {
         ServiceCredentials credentials = this.description.Behaviors.Find <ServiceCredentials>();
         if (credentials != null)
         {
             ServiceCredentials credentials2 = credentials.Clone();
             credentials2.MakeReadOnly();
             this.readOnlyCredentials = credentials2;
         }
         ServiceAuthorizationBehavior behavior = this.description.Behaviors.Find <ServiceAuthorizationBehavior>();
         if (behavior != null)
         {
             ServiceAuthorizationBehavior behavior2 = behavior.Clone();
             behavior2.MakeReadOnly();
             this.readOnlyAuthorization = behavior2;
         }
         ServiceAuthenticationBehavior behavior3 = this.description.Behaviors.Find <ServiceAuthenticationBehavior>();
         if (behavior3 != null)
         {
             ServiceAuthenticationBehavior behavior4 = behavior3.Clone();
             behavior3.MakeReadOnly();
             this.readOnlyAuthentication = behavior4;
         }
         if (ManagementExtension.IsEnabled)
         {
             ManagementExtension.OnServiceOpened(this);
         }
     }
     base.OnOpened();
 }
        public HttpsChannelListener(HttpsTransportBindingElement httpsBindingElement, BindingContext context) : base(httpsBindingElement, context)
        {
            this.requireClientCertificate = httpsBindingElement.RequireClientCertificate;
            SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (manager == null)
            {
                manager = ServiceCredentials.CreateDefaultCredentials();
            }
            SecurityTokenManager tokenManager = manager.CreateSecurityTokenManager();

            this.certificateAuthenticator = TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme, TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress));
            ServiceCredentials credentials = manager as ServiceCredentials;

            if ((credentials != null) && (credentials.ClientCertificate.Authentication.CertificateValidationMode == X509CertificateValidationMode.Custom))
            {
                this.useCustomClientCertificateVerification = true;
            }
            else
            {
                this.useCustomClientCertificateVerification = false;
                X509SecurityTokenAuthenticator certificateAuthenticator = this.certificateAuthenticator as X509SecurityTokenAuthenticator;
                if (certificateAuthenticator != null)
                {
                    this.certificateAuthenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None, certificateAuthenticator.MapCertificateToWindowsAccount, base.ExtractGroupsForWindowsAccounts, false);
                }
            }
            if (this.RequireClientCertificate && (base.AuthenticationScheme != AuthenticationSchemes.Anonymous))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new InvalidOperationException(System.ServiceModel.SR.GetString("HttpAuthSchemeAndClientCert", new object[] { base.AuthenticationScheme })), TraceEventType.Error);
            }
            this.channelBindingProvider = new ChannelBindingProviderHelper();
        }
Beispiel #17
0
        override protected void InitializeRuntime()
        {
            // Extract the ServiceCredentials behavior or create one.
            ServiceCredentials serviceCredentials = this.Description.Behaviors.Find <ServiceCredentials>();

            if (serviceCredentials == null)
            {
                serviceCredentials = new ServiceCredentials();
                this.Description.Behaviors.Add(serviceCredentials);
            }

            // Set the service certificate.
            serviceCredentials.ServiceCertificate.SetCertificate("CN=localhost");

            /*
             * Setting the CertificateValidationMode to PeerOrChainTrust means that if the certificate
             * is in the Trusted People store, then it is trusted without performing a
             * validation of the certificate's issuer chain. This setting is used here for convenience so that the
             * sample can be run without having to have certificates issued by a certificate authority (CA).
             * This setting is less secure than the default, ChainTrust. The security implications of this
             * setting should be carefully considered before using PeerOrChainTrust in production code.
             */
            serviceCredentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;

            // Create the custom binding and add an endpoint to the service.
            Binding multipleTokensBinding = BindingHelper.CreateMultiFactorAuthenticationBinding();

            this.AddServiceEndpoint(typeof(IEchoService), multipleTokensBinding, string.Empty);

            base.InitializeRuntime();
        }
        protected override IChannelListener <TChannel> BuildChannelListenerCore <TChannel>(BindingContext context)
        {
            bool           requireDemuxer = RequiresChannelDemuxer();
            ChannelBuilder channelBuilder = new ChannelBuilder(context, requireDemuxer);

            if (requireDemuxer)
            {
                ApplyPropertiesOnDemuxer(channelBuilder, context);
            }
            BindingContext issuerBindingContext = context.Clone();

            SecurityChannelListener <TChannel> channelListener    = new SecurityChannelListener <TChannel>(this, context);
            SecurityCredentialsManager         credentialsManager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialsManager == null)
            {
                credentialsManager = ServiceCredentials.CreateDefaultCredentials();
            }

            SecurityProtocolFactory protocolFactory = this.CreateSecurityProtocolFactory <TChannel>(context, credentialsManager, true, issuerBindingContext);

            channelListener.SecurityProtocolFactory = protocolFactory;
            channelListener.InitializeListener(channelBuilder);

            return(channelListener);
        }
        protected internal override object CreateBehavior()
        {
            var sb = new ServiceCredentials();

            ApplyConfiguration(sb);
            return(sb);
        }
Beispiel #20
0
        static PeerSecurityCredentialsManager GetCredentialsManager(PeerAuthenticationMode mode, bool signing, BindingContext context)
        {
            if (mode == PeerAuthenticationMode.None && !signing)
            {
                return(null);
            }
            ClientCredentials clientCredentials = context.BindingParameters.Find <ClientCredentials>();

            if (clientCredentials != null)
            {
                return(new PeerSecurityCredentialsManager(clientCredentials.Peer, mode, signing));
            }
            ServiceCredentials serviceCredentials = context.BindingParameters.Find <ServiceCredentials>();

            if (serviceCredentials != null)
            {
                return(new PeerSecurityCredentialsManager(serviceCredentials.Peer, mode, signing));
            }
            SecurityCredentialsManager credman = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credman == null)
            {
                PeerExceptionHelper.ThrowArgument_InsufficientCredentials(PeerPropertyNames.Credentials);
            }
            return(new PeerSecurityCredentialsManager(credman.CreateSecurityTokenManager(), mode, signing));
        }
Beispiel #21
0
    public static void Main()
    {
        ServiceHost   host    = new ServiceHost(typeof(Foo));
        WSHttpBinding binding = new WSHttpBinding();

        binding.Security.Message.EstablishSecurityContext   = false;
        binding.Security.Message.NegotiateServiceCredential = false;
        binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
        binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
        host.AddServiceEndpoint("IFoo",
                                binding, new Uri("http://localhost:8080"));
        host.Description.Behaviors.Find <ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = true;
        ServiceCredentials cred = new ServiceCredentials();

        cred.ServiceCertificate.Certificate = new X509Certificate2("test.pfx", "mono");
        cred.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
        cred.UserNameAuthentication.CustomUserNamePasswordValidator =
            new GodUserNamePasswordValidator();
        host.Description.Behaviors.Add(cred);
        foreach (ServiceEndpoint se in host.Description.Endpoints)
        {
            se.Behaviors.Add(new StdErrInspectionBehavior());
        }
        host.Open();
        Console.WriteLine("Hit [CR] key to close ...");
        Console.ReadLine();
        host.Close();
    }
        /// <summary>
        /// Creates the service host.
        /// </summary>
        /// <param name="t">The t.</param>
        /// <param name="baseAddresses">The base addresses.</param>
        /// <returns>ServiceHost.</returns>
        protected override ServiceHost CreateServiceHost(Type t, Uri[] baseAddresses)
        {
            var serviceHost = new ServiceHost(t, baseAddresses);

            serviceHost.PrintHostInfo();

            var bnd = BindingFactory.CreateBindingFromKey(BindingFactory.Key.CustomValidationBasicHttpBindingTransportAndMessage);

            serviceHost.AddServiceEndpoint(typeof(IAuthentication), bnd, "");

            var scb = new ServiceCredentials();

            scb.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
            scb.UserNameAuthentication.CustomUserNamePasswordValidator = new Authentications();
            scb.ServiceCertificate.SetCertificate(CertificateHelper.GetStoreLocation(),
                                                  CertificateHelper.GetStoreName(),
                                                  X509FindType.FindBySubjectName,
                                                  CertificateHelper.GetCertificateSubject());

            serviceHost.Description.Behaviors.Add(scb);

            serviceHost.MakeAnnouncingService();

            serviceHost.PrintListeningEndpoints();

            return(serviceHost);
        }
Beispiel #23
0
        public void Start()
        {
            // auth
            var serviceCredentials = new ServiceCredentials();

            serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode  = UserNamePasswordValidationMode.Custom;
            serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new ServiceAuthenticator();

            servidor.Description.Behaviors.Add(serviceCredentials);

            // bind
            var binding = new BasicHttpBinding();

            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;

            servidor.AddServiceEndpoint(
                typeof(IProdutoService),
                binding,
                "Produto.svc"
                );

            // mex
            servidor.Description.Behaviors.Add(new ServiceMetadataBehavior());
            servidor.AddServiceEndpoint(
                typeof(IMetadataExchange),
                MetadataExchangeBindings.CreateMexHttpBinding(),
                "mex"
                );

            servidor.Open();
        }
Beispiel #24
0
            private void Snippet6And7()
            {
                //<snippet6>
                ServiceHost myServiceHost = new ServiceHost(typeof(CalculatorService));

                // Specify client credentials validation on the service.
                ServiceCredentials myServiceCredentials =
                    myServiceHost.Description.Behaviors.Find <ServiceCredentials>();

                // The CurrentUser property of the StoreLocation class is a static method.
                myServiceCredentials.ClientCertificate.Authentication.TrustedStoreLocation =
                    StoreLocation.CurrentUser;
                //</snippet6>

                //<snippet7>
                WSHttpBinding binding = new WSHttpBinding();

                binding.Security.Mode = SecurityMode.Message;
                binding.Security.Message.ClientCredentialType =
                    MessageCredentialType.UserName;
                binding.Security.Message.NegotiateServiceCredential = false;

                CalculatorClient CalculatorClient = new CalculatorClient("myBinding");

                CalculatorClient.ClientCredentials.ServiceCertificate.
                SetDefaultCertificate("Al", StoreLocation.CurrentUser, StoreName.My);
                //</snippet7>
            }
Beispiel #25
0
        public static SslStreamSecurityUpgradeProvider CreateServerProvider(SslStreamSecurityBindingElement bindingElement, BindingContext context)
        {
            SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (manager == null)
            {
                manager = ServiceCredentials.CreateDefaultCredentials();
            }
            Uri listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            SecurityTokenManager tokenManager = manager.CreateSecurityTokenManager();
            RecipientServiceModelSecurityTokenRequirement tokenRequirement = new RecipientServiceModelSecurityTokenRequirement {
                TokenType = SecurityTokenTypes.X509Certificate,
                RequireCryptographicToken = true,
                KeyUsage        = SecurityKeyUsage.Exchange,
                TransportScheme = context.Binding.Scheme,
                ListenUri       = listenUri
            };
            SecurityTokenProvider serverTokenProvider = tokenManager.CreateSecurityTokenProvider(tokenRequirement);

            if (serverTokenProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ClientCredentialsUnableToCreateLocalTokenProvider", new object[] { tokenRequirement })));
            }
            return(new SslStreamSecurityUpgradeProvider(context.Binding, serverTokenProvider, bindingElement.RequireClientCertificate, TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme, listenUri), context.Binding.Scheme, bindingElement.IdentityVerifier));
        }
Beispiel #26
0
        public void SecureConversationAuthentication()
        {
            SecureConversationServiceCredential sc =
                new ServiceCredentials().SecureConversationAuthentication;

            Assert.AreEqual(5, sc.SecurityContextClaimTypes.Count, "#1");
            Collection <Type> types = new Collection <Type> (new Type [] {
                typeof(SamlAuthorizationDecisionClaimResource),
                typeof(SamlAuthenticationClaimResource),
                typeof(SamlAccessDecision),
                typeof(SamlAuthorityBinding),
                typeof(SamlNameIdentifierClaimResource)
            });

            foreach (Type type in sc.SecurityContextClaimTypes)
            {
                if (!types.Contains(type))
                {
                    Assert.Fail(type.ToString());
                }
            }
            DataProtectionSecurityStateEncoder sse = sc.SecurityStateEncoder
                                                     as DataProtectionSecurityStateEncoder;

            Assert.IsNotNull(sse, "#2-1");
            Assert.IsTrue(sse.UseCurrentUserProtectionScope, "#2-2");
        }
        public void CheckDuplicateAuthenticatorTypesService()
        {
            SymmetricSecurityBindingElement be =
                new SymmetricSecurityBindingElement();

            be.ProtectionTokenParameters =
                new X509SecurityTokenParameters();
            be.EndpointSupportingTokenParameters.Endorsing.Add(
                new X509SecurityTokenParameters());
            // This causes multiple supporting token authenticator
            // of the same type.
            be.OptionalEndpointSupportingTokenParameters.Endorsing.Add(
                new X509SecurityTokenParameters());
            Binding            b    = new CustomBinding(be, new HttpTransportBindingElement());
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            IChannelListener <IReplyChannel> ch = b.BuildChannelListener <IReplyChannel> (new Uri("http://localhost:" + NetworkHelpers.FindFreePort()), cred);

            try {
                ch.Open();
            } finally {
                if (ch.State == CommunicationState.Closed)
                {
                    ch.Close();
                }
            }
        }
        public void ClientAcceptUpgrade()
        {
            ServiceCredentials cred = new ServiceCredentials();
            X509Certificate2   cert =
                new X509Certificate2("Test/Resources/test.cer");

            cred.ServiceCertificate.Certificate = cert;
            X509CertificateEndpointIdentity ident =
                new X509CertificateEndpointIdentity(cert);
            StreamSecurityUpgradeProvider p = CreateClientProvider(cred, ident);

            p.Open();
            try
            {
                StreamSecurityUpgradeAcceptor a =
                    p.CreateUpgradeAcceptor()
                    as StreamSecurityUpgradeAcceptor;
                Assert.IsNotNull(a, "#1");
                SecurityMessageProperty prop =
                    a.GetRemoteSecurity();
                Assert.IsNull(prop, "#2"); // hmm
                Stream s = a.AcceptUpgrade(new MemoryStream(new byte [] { 1, 2, 3, 4, 5 }));
            }
            finally
            {
                p.Close();
            }
        }
        static void DemanAspNetProvidersPermissions(ServiceHost host)
        {
            bool demand = false;

            foreach (IServiceBehavior behavior in host.Description.Behaviors)
            {
                if (behavior is ServiceCredentials)
                {
                    ServiceCredentials credentialsBehavior = behavior as ServiceCredentials;
                    if (credentialsBehavior.UserNameAuthentication.UserNamePasswordValidationMode == UserNamePasswordValidationMode.MembershipProvider)
                    {
                        demand = true;
                        break;
                    }
                }
                if (behavior is ServiceAuthorizationBehavior)
                {
                    ServiceAuthorizationBehavior serviceAuthorization = behavior as ServiceAuthorizationBehavior;
                    if (serviceAuthorization.PrincipalPermissionMode == PrincipalPermissionMode.UseAspNetRoles && Roles.Enabled)
                    {
                        demand = true;
                        break;
                    }
                }
            }
            if (demand)
            {
                IPermission permission = new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal);
                permission.Demand();
            }
        }
Beispiel #30
0
        public void RejectInclusionModeNever()
        {
            AsymmetricSecurityBindingElement sbe =
                new AsymmetricSecurityBindingElement();

            sbe.InitiatorTokenParameters = sbe.RecipientTokenParameters =
                new X509SecurityTokenParameters(
                    X509KeyIdentifierClauseType.Thumbprint,
                    // this leads to the failure.
                    SecurityTokenInclusionMode.Never);
            ServiceHost host = new ServiceHost(typeof(Foo));
            HttpTransportBindingElement hbe =
                new HttpTransportBindingElement();
            CustomBinding binding = new CustomBinding(sbe, hbe);

            host.AddServiceEndpoint(typeof(IFoo),
                                    binding, new Uri("http://localhost:37564"));
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2("Test/Resources/test.pfx", "mono");
            cred.ClientCertificate.Authentication.CertificateValidationMode =
                X509CertificateValidationMode.None;
            host.Description.Behaviors.Add(cred);
            try {
                host.Open();
            } finally {
                if (host.State == CommunicationState.Opened)
                {
                    host.Close();
                }
            }
        }
        public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
                                                    BindingContext context, bool isClient)
            : base(context.Binding)
        {
            ExtractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            ProtectionLevel = bindingElement.ProtectionLevel;
            Scheme          = context.Binding.Scheme;
            _isClient       = isClient;
            _listenUri      = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);

            SecurityCredentialsManager credentialProvider = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                //if (isClient)
                //{
                //    credentialProvider = ClientCredentials.CreateDefaultCredentials();
                //}
                //else
                //{
                credentialProvider = new ServiceCredentials(); //ServiceCredentials.CreateDefaultCredentials();
                //}
            }

            if (credentialProvider is ServiceCredentials)
            {
                ServiceCredentials serviceCred = (ServiceCredentials)credentialProvider;
                LdapSettings = serviceCred.WindowsAuthentication.LdapSetting;
            }
            _securityTokenManager = credentialProvider.CreateSecurityTokenManager();
        }
Beispiel #32
0
 public ServiceCredentialsSecurityTokenManager(ServiceCredentials parent)
 {
     if (parent == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parent));
     }
     this.parent = parent;
 }
Beispiel #33
0
	public static void Main ()
	{
		AsymmetricSecurityBindingElement sbe =
			new AsymmetricSecurityBindingElement ();
		//sbe.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
		//sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
		//sbe.RequireSignatureConfirmation = true;

		//sbe.LocalServiceSettings.DetectReplays = false;
		//sbe.IncludeTimestamp = false;

		sbe.RecipientTokenParameters =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
		sbe.InitiatorTokenParameters = 
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.AlwaysToRecipient);
		X509SecurityTokenParameters p =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.AlwaysToRecipient);
		p.RequireDerivedKeys = false;
		//sbe.EndpointSupportingTokenParameters.Endorsing.Add (p);
		UserNameSecurityTokenParameters up =
			new UserNameSecurityTokenParameters ();
		sbe.EndpointSupportingTokenParameters.Signed.Add (up);
		sbe.SetKeyDerivation (false);
		sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		cred.UserNameAuthentication.UserNamePasswordValidationMode =
			UserNamePasswordValidationMode.Custom;
		cred.UserNameAuthentication.CustomUserNamePasswordValidator =
			UserNamePasswordValidator.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		foreach (ServiceEndpoint se in host.Description.Endpoints)
			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #34
0
	public static void Main ()
	{
		ServiceHost host = new MyHost (typeof (Foo));
		var sc = new ServiceCredentials ();
		sc.UserNameAuthentication.UserNamePasswordValidationMode =
			UserNamePasswordValidationMode.Custom;
		sc.UserNameAuthentication.CustomUserNamePasswordValidator =
			UserNamePasswordValidator.None;
		host.Description.Behaviors.Add (sc);
		var binding = new BasicHttpBinding ();
		binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
		binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo", binding, new Uri ("http://localhost:8080"));
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #35
0
	public static void Main ()
	{
Console.WriteLine ("WARNING!! This test is not configured enought to work fine on .NET either.");

		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
		sbe.RequireSignatureConfirmation = true;
		//sbe.IncludeTimestamp = false;

		sbe.ProtectionTokenParameters =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
		X509SecurityTokenParameters p =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.AlwaysToRecipient);
		p.RequireDerivedKeys = false;
		sbe.EndpointSupportingTokenParameters.Endorsing.Add (p);
		//sbe.SetKeyDerivation (false);
		//sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
		ServiceHost host = new ServiceHost (typeof (Foo));
		var mbe = new BinaryMessageEncodingBindingElement ();
		var tbe = new TcpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, mbe, tbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #36
0
	public static void Main ()
	{
		ServiceHost host = new ServiceHost (typeof (Foo));
		var binding = new NetTcpBinding ();
		binding.Security.Mode = SecurityMode.Message;
		binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("net.tcp://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #37
0
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		//sbe.IncludeTimestamp = false;
		//sbe.LocalServiceSettings.DetectReplays = false;

		sbe.ProtectionTokenParameters = new X509SecurityTokenParameters ();
		// This "Never" is somehow mandatory (though I wonder why ...)
		sbe.ProtectionTokenParameters.InclusionMode = SecurityTokenInclusionMode.Never;

		sbe.SetKeyDerivation (false);
		sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		foreach (ServiceEndpoint se in host.Description.Endpoints)
			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #38
0
	public static void Main (string [] args)
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		IssuedSecurityTokenParameters ip =
			new IssuedSecurityTokenParameters ();
		sbe.ProtectionTokenParameters = ip;
		ip.ClaimTypeRequirements.Add (new ClaimTypeRequirement (
			ClaimTypes.Email));
		if (args.Length > 0) {
			ip.IssuerAddress = new EndpointAddress (new Uri (args [0]),
				new X509CertificateEndpointIdentity (new X509Certificate2 (args [1])));
		}
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		cred.IssuedTokenAuthentication.AllowUntrustedRsaIssuers = true;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
Beispiel #39
0
 /// <summary>
 /// Constructs MNSClient with Aliyun Service Credentials.
 /// </summary>
 /// <param name="credentials">Aliyun Service Credentials</param>
 /// <param name="regionEndpoint">The region endpoint to connect.</param>
 public MNSClient(ServiceCredentials credentials, String regionEndpoint)
     : this(credentials, new MNSConfig { RegionEndpoint = new Uri(regionEndpoint) })
 {
 }
Beispiel #40
0
 /// <summary>
 /// Constructs MNSClient with Aliyun Service Credentials and an
 /// MNSClient Configuration object.
 /// </summary>
 /// <param name="credentials">Aliyun Service Credentials</param>
 /// <param name="clientConfig">The MNSClient Configuration Object</param>
 public MNSClient(ServiceCredentials credentials, MNSConfig clientConfig)
     : base(credentials, clientConfig)
 {
 }
 /// <summary>
 /// The constructor for CredentialsRetriever.
 /// </summary>
 /// <param name="credentials">An Service Credentials instance.</param>
 public CredentialsRetriever(ServiceCredentials credentials)
 {
     this.Credentials = credentials;
 }