public override void createTestFixture()
        {
            BodyArchitectAccessService.EnableLog(false);//to invoke static constructor which set Log to true
            base.createTestFixture();

            ExceptionHandler.Default.EmailFeaturesEnabled = false;
            //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

            var baseAddress = new Uri("http://localhost:8000/TestService");

            myServiceHost_ = new ServiceHost(typeof(ServiceClass), baseAddress);
            binding        = new BasicHttpBinding();

            myServiceHost_.AddServiceEndpoint(typeof(IService), binding, address);
            myServiceHost_.Description.Behaviors.Remove(typeof(ServiceAuthorizationBehavior));
            var apiKeyAuthorization = new ServiceAuthorizationBehavior();

            apiKeyAuthorization.ServiceAuthorizationManager = new APIKeyAuthorization();
            myServiceHost_.Description.Behaviors.Add(apiKeyAuthorization);

            var smb = new ServiceMetadataBehavior {
                HttpGetEnabled = true
            };

            myServiceHost_.Description.Behaviors.Add(smb);
            myServiceHost_.Open();
        }
 public void Can_Apply_PrincipalPermissionModeAuthorization()
 {
     using (IWindsorContainer container = Container)
     {
         container.Register(
             Component.For <PrincipalPermissionModeAuthorization>()
             .DependsOn(new { principalPermissionMode = PrincipalPermissionMode.Custom })
             .Attribute(WcfConstants.ExtensionScopeKey).Eq(WcfExtensionScope.Services),
             Component.For <IOperations>()
             .ImplementedBy <Operations>()
             .LifeStyle.Transient
             .AsWcfService(
                 new DefaultServiceModel()
                 .AddEndpoints(WcfEndpoint
                               .BoundTo(new NetTcpBinding {
             PortSharingEnabled = true
         })
                               .At("net.tcp://localhost/Operations"))));
         WcfFacility wcfFacility = container.Kernel.GetFacilities().OfType <WcfFacility>().Single();
         ServiceHost host        = wcfFacility.Services.ManagedServiceHosts.Single();
         ServiceAuthorizationBehavior serviceAuthorizationBehavior = host.Description.Behaviors.OfType <ServiceAuthorizationBehavior>().SingleOrDefault();
         Assert.IsNotNull(serviceAuthorizationBehavior);
         Assert.AreEqual(PrincipalPermissionMode.Custom, serviceAuthorizationBehavior.PrincipalPermissionMode);
     }
 }
 public static IServiceCollection AddServiceModelServices(this IServiceCollection services)
 {
     if (services == null)
     {
         throw new ArgumentNullException(nameof(services));
     }
     services.AddSingleton <ServiceBuilder>();
     services.AddSingleton <IServiceBuilder>(provider => provider.GetRequiredService <ServiceBuilder>());
     services.AddSingleton <IServiceBehavior>(provider => provider.GetRequiredService <ServiceAuthorizationBehavior>());
     services.AddSingleton <ServiceAuthorizationBehavior>(provider =>
     {
         var behavior = new ServiceAuthorizationBehavior();
         var manager  = provider.GetService <ServiceAuthorizationManager>();
         if (manager != null)
         {
             behavior.ServiceAuthorizationManager = manager;
         }
         return(behavior);
     });
     services.TryAddSingleton(typeof(IServiceConfiguration <>), typeof(ServiceConfiguration <>));
     services.TryAddSingleton <IDispatcherBuilder, DispatcherBuilderImpl>();
     services.AddSingleton(typeof(ServiceConfigurationDelegateHolder <>));
     services.AddScoped <ReplyChannelBinder>();
     services.AddScoped <DuplexChannelBinder>();
     services.AddScoped <InputChannelBinder>();
     services.AddScoped <ServiceChannel.SessionIdleManager>();
     services.AddSingleton(typeof(ServiceHostObjectModel <>));
     services.AddSingleton(typeof(TransportCompressionSupportHelper));
     return(services);
 }
Exemple #4
0
        /// <summary>
        /// Creates a new <see cref="DataServiceHost"/> from the URI.
        /// </summary>
        /// <param name="serviceType">Specifies the type of WCF service to host.</param>
        /// <param name="baseAddresses">An array of base addresses for the service.</param>
        /// <returns>New <see cref="DataServiceHost"/>.</returns>
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            // Create data service host.
            ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);

            // Enable security on the data service.
            ServiceAuthorizationBehavior serviceBehavior = host.Description.Behaviors.Find <ServiceAuthorizationBehavior>();

            if (serviceBehavior == null)
            {
                serviceBehavior = new ServiceAuthorizationBehavior();
                host.Description.Behaviors.Add(serviceBehavior);
            }
            serviceBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();

            policies.Add((IAuthorizationPolicy)Activator.CreateInstance(m_authorizationPolicy));
            serviceBehavior.ExternalAuthorizationPolicies = policies.AsReadOnly();

            foreach (var behavior in m_serviceBehaviors ?? new List <IServiceBehavior>())
            {
                host.Description.Behaviors.Add(behavior);
            }

            foreach (var endpoint in host.Description.Endpoints)
            {
                foreach (var behavior in m_endpointBehaviors ?? new List <IEndpointBehavior>())
                {
                    endpoint.EndpointBehaviors.Add(behavior);
                }
            }

            return(host);
        }
        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();
            }
        }
Exemple #6
0
        protected virtual void ApplyConfiguration()
        {
            if (Description == null)
            {
                throw new InvalidOperationException("ApplyConfiguration requires that the Description property be initialized. Either provide a valid ServiceDescription in the CreateDescription method or override the ApplyConfiguration method to provide an alternative implementation");
            }

            ServiceElement service = GetServiceElement();

            if (service != null)
            {
                LoadConfigurationSection(service);
            }
            // simplified configuration
            AddServiceBehaviors(String.Empty, false);
            // TODO: consider commonBehaviors here

            // ensure ServiceAuthorizationBehavior
            Authorization = Description.Behaviors.Find <ServiceAuthorizationBehavior> ();
            if (Authorization == null)
            {
                Authorization = new ServiceAuthorizationBehavior();
                Description.Behaviors.Add(Authorization);
            }

            // ensure ServiceDebugBehavior
            ServiceDebugBehavior debugBehavior = Description.Behaviors.Find <ServiceDebugBehavior> ();

            if (debugBehavior == null)
            {
                debugBehavior = new ServiceDebugBehavior();
                Description.Behaviors.Add(debugBehavior);
            }
        }
Exemple #7
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();
 }
        /// <summary>
        /// Adds the service authorization behavior based on configuration
        /// </summary>
        /// <param name="serviceBehaviors"></param>
        public static void SetServiceAuthorizationBehavior(
            this KeyedByTypeCollection <IServiceBehavior> serviceBehaviors
            )
        {
            bool addNewEntry = false;
            var  serviceAuthorizationBehavior =
                serviceBehaviors.Find <ServiceAuthorizationBehavior>();

            if (serviceAuthorizationBehavior == null)
            {
                addNewEntry = true;
                serviceAuthorizationBehavior = new ServiceAuthorizationBehavior();
            }
            Console.WriteLine("Added service behavior with user group access");
            serviceAuthorizationBehavior.PrincipalPermissionMode =
                PrincipalPermissionMode.UseWindowsGroups;
            serviceAuthorizationBehavior.ServiceAuthorizationManager =
                new SecuredServiceAuthorizationManager(new List <string>()
            {
                "BUILTIN\\Administrators", "NT AUTHORITY\\SYSTEM", "CODE1\\gd_IN_Employees_HT"
            }, new List <string>()
            {
                "Test1"
            });
            if (addNewEntry)
            {
                serviceBehaviors.Add(serviceAuthorizationBehavior);
            }
        }
        public void Validate()
        {
            var b = new ServiceAuthorizationBehavior();
            IServiceBehavior sb = b;

            sb.Validate(new ServiceDescription(),
                        new ServiceHost(typeof(object)));
        }
Exemple #10
0
        protected virtual ServiceEndpoint AddCommonEndpoints(Type type, ServiceHost sh, string path, bool withMex,
                                                             bool authPolicy, int serverListenPort)
        {
            NetTcpBinding binding = Channels.GetBinding(Settings.Default.AllowClients);

            var address = new Uri(string.Format("net.tcp://localhost:{0}/{1}",
                                                serverListenPort,
                                                path));
            ServiceEndpoint endpoint = sh.AddServiceEndpoint(type, binding, address);

            ServiceMetadataBehavior smb = sh.Description.Behaviors.Find <ServiceMetadataBehavior>()
                                          ?? new ServiceMetadataBehavior();

            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            smb.HttpGetEnabled = true;
            if (sh.Description.Behaviors.Find <ServiceMetadataBehavior>() == null)
            {
                sh.Description.Behaviors.Add(smb);
            }

            ServiceThrottlingBehavior throttle = sh.Description.Behaviors.Find <ServiceThrottlingBehavior>()
                                                 ?? new ServiceThrottlingBehavior();

            throttle.MaxConcurrentSessions = Settings.Default.AllowClients;
            if (sh.Description.Behaviors.Find <ServiceThrottlingBehavior>() == null)
            {
                sh.Description.Behaviors.Add(throttle);
            }

            if (authPolicy && Settings.Default.ClaimsSecurityEnabled)
            {
                ServiceAuthorizationBehavior auth = sh.Description.Behaviors.Find <ServiceAuthorizationBehavior>()
                                                    ?? new ServiceAuthorizationBehavior();
                auth.ExternalAuthorizationPolicies = new ReadOnlyCollection <IAuthorizationPolicy>
                                                         (new[] { new ClaimsPolicy() });
                if (sh.Description.Behaviors.Find <ServiceAuthorizationBehavior>() == null)
                {
                    sh.Description.Behaviors.Add(auth);
                }
            }

            if (withMex)
            {
                sh.AddServiceEndpoint(
                    ServiceMetadataBehavior.MexContractName,
                    MetadataExchangeBindings.CreateMexHttpBinding(),
                    "mex");
            }

            sh.UnknownMessageReceived += service_UnknownMessageReceived;

#if DEBUG
            ((ServiceDebugBehavior)sh.Description.Behaviors[typeof(ServiceDebugBehavior)])
            .IncludeExceptionDetailInFaults = true;
#endif
            return(endpoint);
        }
Exemple #11
0
        private ServiceAuthorizationBehavior EnsureAuthorization(System.ServiceModel.Description.ServiceDescription description)
        {
            ServiceAuthorizationBehavior item = description.Behaviors.Find <ServiceAuthorizationBehavior>();

            if (item == null)
            {
                item = new ServiceAuthorizationBehavior();
                description.Behaviors.Add(item);
            }
            return(item);
        }
Exemple #12
0
        /// <summary>
        /// Start session launcher service
        /// </summary>
        private void StartSessionLauncherService()
        {
            try
            {
                string sessionLauncherAddress = SoaHelper.GetSessionLauncherAddress("localhost");
                this.launcherHost = new ServiceHost(this.sessionLauncher, new Uri(sessionLauncherAddress));
                BindingHelper.ApplyDefaultThrottlingBehavior(this.launcherHost);

#if AZURE_STORAGE_BINDING
                if (SessionLauncherRuntimeConfiguration.OpenAzureStorageListener)
                {
                    this.launcherHost.AddServiceEndpoint(
                        typeof(ISessionLauncher),
                        new TableTransportBinding()
                    {
                        ConnectionString = SessionLauncherRuntimeConfiguration.SessionLauncherStorageConnectionString, TargetPartitionKey = "all"
                    },
                        TelepathyConstants.SessionLauncherAzureTableBindingAddress);
                    TraceHelper.TraceEvent(TraceEventType.Information, "Add session launcher service endpoint {0}", TelepathyConstants.SessionLauncherAzureTableBindingAddress);
                }
#endif

                if (SessionLauncherRuntimeConfiguration.SchedulerType == SchedulerType.HpcPack)
                {
                    this.launcherHost.AddServiceEndpoint(typeof(ISessionLauncher), BindingHelper.HardCodedSessionLauncherNetTcpBinding, string.Empty);
                    this.launcherHost.AddServiceEndpoint(typeof(ISessionLauncher), BindingHelper.HardCodedNoAuthSessionLauncherNetTcpBinding, "AAD");
                    this.launcherHost.AddServiceEndpoint(typeof(ISessionLauncher), BindingHelper.HardCodedInternalSessionLauncherNetTcpBinding, "Internal");

                    TraceHelper.TraceEvent(TraceEventType.Information, "Open session launcher find cert {0}", TelepathyContext.Get().GetSSLThumbprint().GetAwaiter().GetResult());
                    this.launcherHost.Credentials.UseInternalAuthenticationAsync().GetAwaiter().GetResult();

                    TraceHelper.TraceEvent(TraceEventType.Information, "Add session launcher service endpoint {0}", sessionLauncherAddress);
                }
                else
                {
                    this.launcherHost.AddServiceEndpoint(typeof(ISessionLauncher), BindingHelper.HardCodedUnSecureNetTcpBinding, string.Empty);
                    this.launcherHost.AddServiceEndpoint(typeof(ISessionLauncher), BindingHelper.HardCodedUnSecureNetTcpBinding, "Internal");

                    TraceHelper.TraceEvent(TraceEventType.Information, "Add session launcher service endpoint {0}", sessionLauncherAddress);
                }

                this.launcherHost.Faulted += this.SessionLauncherHostFaultHandler;
                ServiceAuthorizationBehavior myServiceBehavior =
                    this.launcherHost.Description.Behaviors.Find <ServiceAuthorizationBehavior>();
                myServiceBehavior.PrincipalPermissionMode = PrincipalPermissionMode.None;
                this.launcherHost.Open();
                TraceHelper.TraceEvent(TraceEventType.Information, "Open session launcher service");
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                throw;
            }
        }
Exemple #13
0
        public void DefaultValues()
        {
            ServiceAuthorizationBehavior b =
                new ServiceAuthorizationBehavior();

            Assert.IsNull(b.AuthorizationDomain, "#1");
            Assert.IsFalse(b.ImpersonateCallerForAllServiceOperations,
                           "#2");
            Assert.IsNull(b.OperationRequirement, "#3");
            Assert.AreEqual(PrincipalPermissionMode.UseWindowsGroups,
                            b.PrincipalPermissionMode, "#4");
        }
Exemple #14
0
        public static void Main()
        {
            Uri baseUri = new Uri("http://ServiceModelSamples");

            //<snippet3>
            ServiceHost myServiceHost = new ServiceHost(typeof(Calculator), baseUri);
            ServiceAuthorizationBehavior myServiceBehavior =
                myServiceHost.Description.Behaviors.Find <ServiceAuthorizationBehavior>();

            myServiceBehavior.PrincipalPermissionMode =
                PrincipalPermissionMode.UseAspNetRoles;
            //</snippet3>
        }
Exemple #15
0
        private ServiceAuthorizationBehavior EnsureAuthorization(ServiceDescription description)
        {
            Fx.Assert(State == CommunicationState.Created || State == CommunicationState.Opening, "");
            ServiceAuthorizationBehavior a = description.Behaviors.Find <ServiceAuthorizationBehavior>();

            if (a == null)
            {
                a = new ServiceAuthorizationBehavior();
                description.Behaviors.Add(a);
            }

            return(a);
        }
Exemple #16
0
        protected internal override object CreateBehavior()
        {
            ServiceAuthorizationBehavior behavior = new ServiceAuthorizationBehavior();

            behavior.PrincipalPermissionMode = this.PrincipalPermissionMode;
            string roleProviderName = this.RoleProviderName;

            if (!String.IsNullOrEmpty(roleProviderName))
            {
                behavior.RoleProvider = SystemWebHelper.GetRoleProvider(roleProviderName);
                if (behavior.RoleProvider == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(
                                                                                  SR.GetString(SR.InvalidRoleProviderSpecifiedInConfig, roleProviderName)));
                }
            }

            behavior.ImpersonateCallerForAllOperations = this.ImpersonateCallerForAllOperations;
            behavior.ImpersonateOnSerializingReply     = this.ImpersonateOnSerializingReply;

            string serviceAuthorizationManagerType = this.ServiceAuthorizationManagerType;

            if (!String.IsNullOrEmpty(serviceAuthorizationManagerType))
            {
                Type type = Type.GetType(serviceAuthorizationManagerType, true);
                if (!typeof(ServiceAuthorizationManager).IsAssignableFrom(type))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(
                                                                                  SR.GetString(SR.ConfigInvalidServiceAuthorizationManagerType, serviceAuthorizationManagerType, typeof(ServiceAuthorizationManager))));
                }
                behavior.ServiceAuthorizationManager = (ServiceAuthorizationManager)Activator.CreateInstance(type);
            }
            AuthorizationPolicyTypeElementCollection authorizationPolicies = this.AuthorizationPolicies;

            if (authorizationPolicies.Count > 0)
            {
                List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(authorizationPolicies.Count);
                for (int i = 0; i < authorizationPolicies.Count; ++i)
                {
                    Type type = Type.GetType(authorizationPolicies[i].PolicyType, true);
                    if (!typeof(IAuthorizationPolicy).IsAssignableFrom(type))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(
                                                                                      SR.GetString(SR.ConfigInvalidAuthorizationPolicyType, authorizationPolicies[i].PolicyType, typeof(IAuthorizationPolicy))));
                    }
                    policies.Add((IAuthorizationPolicy)Activator.CreateInstance(type));
                }
                behavior.ExternalAuthorizationPolicies = policies.AsReadOnly();
            }
            return(behavior);
        }
        protected override void OnOpening()
        {
            base.OnOpening();
            foreach (var ep in this.Description.Endpoints)
            {
                if (ep.Behaviors.Find <WebHttpBehavior>() != null)
                {
                    ep.Behaviors.Remove <WebHttpBehavior>();
                    ep.Behaviors.Add(new WebHttpBehavior2()
                    {
                        EnableAspNetCustomErrors = this.EnableAspNetCustomErrors, EnableAutomaticHelpPage = this.EnableAutomaticHelpPage, HelpPageLink = this.HelpPageLink
                    });
                }

                CustomBinding binding = new CustomBinding(ep.Binding);
                if (this.MaxMessageSize != 0)
                {
                    binding.Elements.Find <TransportBindingElement>().MaxReceivedMessageSize = this.MaxMessageSize;
                }
                if (this.TransferMode != TransferMode.Buffered)
                {
                    binding.Elements.Find <HttpTransportBindingElement>().TransferMode = this.TransferMode;
                }
                if (this.ReaderQuotas != null)
                {
                    this.ReaderQuotas.CopyTo(binding.Elements.Find <TextMessageEncodingBindingElement>().ReaderQuotas);
                }
                if (this.Interceptors.Count > 0)
                {
                    binding.Elements.Insert(0, new RequestInterceptorBindingElement(this.Interceptors));
                }
                ep.Binding = binding;
            }
            if (this.MaxConcurrentCalls != 0)
            {
                ServiceThrottlingBehavior throttlingBehavior = this.Description.Behaviors.Find <ServiceThrottlingBehavior>();
                if (throttlingBehavior == null)
                {
                    throttlingBehavior = new ServiceThrottlingBehavior();
                    this.Description.Behaviors.Add(throttlingBehavior);
                }
                throttlingBehavior.MaxConcurrentCalls = this.MaxConcurrentCalls;
            }
            ServiceAuthorizationBehavior authz = this.Description.Behaviors.Find <ServiceAuthorizationBehavior>();

            authz.PrincipalPermissionMode = this.PrincipalPermissionMode;
            if (authz.PrincipalPermissionMode == PrincipalPermissionMode.UseAspNetRoles && authz.RoleProvider == null && Roles.Enabled)
            {
                authz.RoleProvider = Roles.Provider;
            }
        }
        protected override void OnOpening()
        {
            this.CreateEndpoints();

            //if (String.IsNullOrEmpty(this.Description.Namespace) || this.Description.Namespace == "http://tempuri.org/")
            //    this.Description.Namespace = Constants.ServiceNamespace;

            foreach (var endpoint in this.Description.Endpoints)
            {
                if (endpoint.Behaviors.Find <WebHttpBehavior>() != null)
                {
                    endpoint.Behaviors.Remove <WebHttpBehavior>();
                }
                endpoint.Behaviors.Add(new DynamicWebHttpBehavior());
            }

            if (this.Description.Behaviors.Find <ServiceDebugBehavior>() == null)
            {
                var item = new ServiceDebugBehavior
                {
                    IncludeExceptionDetailInFaults = true
                };
                this.Description.Behaviors.Add(item);
            }

            if (this.Description.Behaviors.Find <ServiceAuthorizationBehavior>() == null)
            {
                var item = new ServiceAuthorizationBehavior
                {
                    ImpersonateCallerForAllOperations = true
                };
                this.Description.Behaviors.Add(item);
            }

            if (this.Description.Behaviors.Find <ServiceMetadataBehavior>() == null)
            {
                var item = new ServiceMetadataBehavior
                {
                    MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
                };
                this.Description.Behaviors.Add(item);
            }
            else
            {
                var item = this.Description.Behaviors.Find <ServiceMetadataBehavior>();
                item.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            }

            base.OnOpening();
        }
Exemple #19
0
 public static IServiceCollection AddServiceModelServices(this IServiceCollection services)
 {
     if (services == null)
     {
         throw new ArgumentNullException(nameof(services));
     }
     services.AddSingleton <WrappingIServer>();
     for (int i = 0; i < services.Count; i++)
     {
         if (services[i].ServiceType == typeof(IServer))
         {
             Type implType = services[i].ImplementationType;
             if (!services.Any(d => d.ServiceType == implType))
             {
                 services.AddSingleton(implType);
             }
             services[i] = ServiceDescriptor.Singleton <IServer>((provider) =>
             {
                 var originalIServer        = (IServer)provider.GetRequiredService(implType);
                 var wrappingServer         = provider.GetRequiredService <WrappingIServer>();
                 wrappingServer.InnerServer = originalIServer;
                 return(wrappingServer);
             });
         }
     }
     services.AddSingleton <ServiceBuilder>();
     services.AddSingleton <IServiceBuilder>(provider => provider.GetRequiredService <ServiceBuilder>());
     services.AddSingleton <IServiceBehavior>(provider => provider.GetRequiredService <ServiceAuthorizationBehavior>());
     services.AddSingleton <ServiceAuthorizationBehavior>(provider =>
     {
         var behavior = new ServiceAuthorizationBehavior();
         var manager  = provider.GetService <ServiceAuthorizationManager>();
         if (manager != null)
         {
             behavior.ServiceAuthorizationManager = manager;
         }
         return(behavior);
     });
     services.TryAddSingleton(typeof(IServiceConfiguration <>), typeof(ServiceConfiguration <>));
     services.TryAddSingleton <IDispatcherBuilder, DispatcherBuilderImpl>();
     services.AddSingleton(typeof(ServiceConfigurationDelegateHolder <>));
     services.AddScoped <ReplyChannelBinder>();
     services.AddScoped <DuplexChannelBinder>();
     services.AddScoped <InputChannelBinder>();
     services.AddScoped <ServiceChannel.SessionIdleManager>();
     services.AddSingleton(typeof(ServiceHostObjectModel <>));
     services.AddSingleton(typeof(TransportCompressionSupportHelper));
     return(services);
 }
        public void DefaultValues()
        {
            var b = new ServiceAuthorizationBehavior();

            Assert.IsNull(b.ExternalAuthorizationPolicies, "#1-1");
            Assert.IsFalse(b.ImpersonateCallerForAllOperations, "#1-2");
            Assert.AreEqual(PrincipalPermissionMode.UseWindowsGroups, b.PrincipalPermissionMode, "#1-3");

            ServiceHost host = new ServiceHost(typeof(TestService));

            b = host.Description.Behaviors.Find <ServiceAuthorizationBehavior> ();
            Assert.IsNull(b.ExternalAuthorizationPolicies, "#2-1");
            Assert.IsFalse(b.ImpersonateCallerForAllOperations, "#2-2");
            Assert.AreEqual(PrincipalPermissionMode.UseWindowsGroups, b.PrincipalPermissionMode, "#2-3");
        }
Exemple #21
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            ServiceAuthorizationBehavior authBehavior = app.ApplicationServices.GetRequiredService <ServiceAuthorizationBehavior>();

            authBehavior.PrincipalPermissionMode = principalMode;
            if (isImpersonate)
            {
                authBehavior.ImpersonateCallerForAllOperations = true;
            }

            app.UseServiceModel(builder =>
            {
                builder.AddService <Services.TestService>();
                builder.AddServiceEndpoint <Services.TestService, ServiceContract.ITestService>(new CoreWCF.NetTcpBinding(), WindowsAuthRelativePath);
                builder.AddServiceEndpoint <Services.TestService, ServiceContract.ITestService>(new CoreWCF.NetTcpBinding(SecurityMode.None), NoSecurityRelativePath);
            });
        }
Exemple #22
0
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                ServiceAuthorizationBehavior authBehavior = app.ApplicationServices.GetRequiredService <ServiceAuthorizationBehavior>();
                var authPolicies = new List <IAuthorizationPolicy>
                {
                    new MyTestAuthorizationPolicy()
                };
                var externalAuthPolicies = new ReadOnlyCollection <IAuthorizationPolicy>(authPolicies);

                authBehavior.ExternalAuthorizationPolicies = externalAuthPolicies;
                authBehavior.PrincipalPermissionMode       = PrincipalPermissionMode.None;
                app.UseServiceModel(builder =>
                {
                    builder.AddService <Services.EchoService>();
                    builder.AddServiceEndpoint <Services.EchoService, ServiceContract.IEchoService>(new CoreWCF.BasicHttpBinding(), "/BasicWcfService/basichttp.svc");
                });
            }
Exemple #23
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            ServiceAuthorizationBehavior authBehavior = app.ApplicationServices.GetRequiredService <ServiceAuthorizationBehavior>();
            var authPolicies = new List <IAuthorizationPolicy>
            {
                new MyTestAuthorizationPolicy()
            };
            var externalAuthPolicies = new ReadOnlyCollection <IAuthorizationPolicy>(authPolicies);

            authBehavior.ExternalAuthorizationPolicies = externalAuthPolicies;
            authBehavior.ServiceAuthorizationManager   = new MyTestServiceAuthorizationManager();
            app.UseServiceModel(builder =>
            {
                builder.AddService <Services.TestService>();
                builder.AddServiceEndpoint <Services.TestService, ServiceContract.ITestService>(new CoreWCF.NetTcpBinding(), WindowsAuthRelativePath);
                builder.AddServiceEndpoint <Services.TestService, ServiceContract.ITestService>(new CoreWCF.NetTcpBinding(SecurityMode.None), NoSecurityRelativePath);
            });
        }
Exemple #24
0
        public void ApplyBehavior()
        {
            ServiceHost        host = new ServiceHost(typeof(object));
            EndpointDispatcher d    = new EndpointDispatcher(host, "a", "");
            DispatchRuntime    db   = d.Behavior;
            EndpointDispatcher d2   = new EndpointDispatcher(host, "a", "");
            DispatchRuntime    db2  = d2.Behavior;

            ServiceAuthorizationBehavior b =
                new ServiceAuthorizationBehavior();

            b.ImpersonateCallerForAllServiceOperations = true;
            b.OperationRequirement    = new MyRequirement();
            b.PrincipalPermissionMode = PrincipalPermissionMode.None;

            Collection <DispatchRuntime> c =
                new Collection <DispatchRuntime> (
                    new DispatchRuntime [] { db, db2 });
            Collection <BindingParameterCollection> pc =
                new Collection <BindingParameterCollection> (
                    new BindingParameterCollection [] {
                new BindingParameterCollection()
            });

            ((IServiceBehavior)b).ApplyBehavior(null, host, c, pc);

            Assert.IsNull(db.AuthorizationDomain, "#1-1");
            Assert.IsTrue(db.ImpersonateCallerForAllServiceOperations, "#1-2");
            Assert.AreEqual(typeof(MyRequirement),
                            db.OperationRequirement.GetType(), "#1-3");
            Assert.AreEqual(PrincipalPermissionMode.None,
                            db.PrincipalPermissionMode, "#1-4");
            Assert.IsNull(db2.AuthorizationDomain, "#2-1");
            Assert.IsTrue(db2.ImpersonateCallerForAllServiceOperations, "#2-2");

            /*
             * Assert.AreEqual (typeof (MyRequirement),
             *      db2.OperationRequirement.GetType (), "#2-3");
             * Assert.AreEqual (PrincipalPermissionMode.None,
             *      db2.PrincipalPermissionMode, "#2-4");
             */
        }
Exemple #25
0
        static void Main(string[] args)
        {
            WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

            GenericIdentity anoymousIdentity  = new GenericIdentity("");
            GenericIdentity authenticIdentity = new GenericIdentity("Foo");

            Console.WriteLine(anoymousIdentity.IsAuthenticated);  //false
            Console.WriteLine(authenticIdentity.IsAuthenticated); //true

            var identity1 = Thread.CurrentPrincipal.Identity;
            var identity2 = ServiceSecurityContext.Current.PrimaryIdentity;

            Debug.Assert(object.ReferenceEquals(identity1, identity2));
            //IPrincipal principal = Thread.CurrentPrincipal;
            //if (principal.IsInRole("Adminstrator"))
            //{
            //    //执行授权操作
            //}
            //else {
            //    //异常
            //}

            //wcf  Asp.net Roles 授权模式
            using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
            {
                ServiceAuthorizationBehavior serviceAuthorizationBehavior = host.Description.Behaviors.Find <ServiceAuthorizationBehavior>();
                if (null == serviceAuthorizationBehavior)
                {
                    serviceAuthorizationBehavior = new ServiceAuthorizationBehavior();
                    host.Description.Behaviors.Add(serviceAuthorizationBehavior);
                }
                serviceAuthorizationBehavior.PrincipalPermissionMode = PrincipalPermissionMode.UseAspNetRoles;
                serviceAuthorizationBehavior.RoleProvider            = Roles.Provider;
                host.Open();
            }

            DispatchRuntime

            Console.ReadKey();
        }
Exemple #26
0
        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();
            ServiceDebugBehavior serviceDebugBehavior = base.Description.Behaviors.Find <ServiceDebugBehavior>();

            serviceDebugBehavior.IncludeExceptionDetailInFaults = true;
            ServiceAuthorizationBehavior serviceAuthorizationBehavior = base.Description.Behaviors.Find <ServiceAuthorizationBehavior>();

            serviceAuthorizationBehavior.PrincipalPermissionMode       = PrincipalPermissionMode.Custom;
            serviceAuthorizationBehavior.ExternalAuthorizationPolicies = EcpServiceHostBase.customAuthorizationPolicies;
            serviceAuthorizationBehavior.ServiceAuthorizationManager   = EcpServiceHostBase.rbacAuthorizationManager;
            ContractDescription contract = ContractDescription.GetContract(base.Description.ServiceType);

            foreach (Uri uri in base.BaseAddresses)
            {
                Binding         binding         = this.CreateBinding(uri);
                ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contract, binding, new EndpointAddress(uri, new AddressHeader[0]));
                serviceEndpoint.Behaviors.Add(EcpServiceHostBase.diagnosticsBehavior);
                this.ApplyServiceEndPointConfiguration(serviceEndpoint);
                base.Description.Endpoints.Add(serviceEndpoint);
            }
        }
Exemple #27
0
        public static ServiceConfiguration ApplyCustomAuthentication
            (this ServiceConfiguration config, Type serviceType, string address)
        {
            config.Credentials.IdentityConfiguration    = CreateIdentityConfiguration();
            config.Credentials.UseIdentityConfiguration = true;
            config.Description.Behaviors.Add(new ServiceMetadataBehavior {
                HttpGetEnabled = true
            });
            config.Description.Behaviors.Add(new ServiceDebugBehavior {
                IncludeExceptionDetailInFaults = true
            });

            var behavior = new ServiceAuthorizationBehavior
            {
                PrincipalPermissionMode = PrincipalPermissionMode.Always
            };

            config.Description.Behaviors.Add(behavior);

            config.AddServiceEndpoint(serviceType, ServiceBinding.CreateBinding(), address);
            return(config);
        }
Exemple #28
0
        private void ServiceAuthorizationBehaviorStuff()
        {
            Uri myUri = new Uri("hello");

            Uri[]       addresses   = new Uri[] { myUri };
            Type        c           = typeof(HelloService);
            ServiceHost serviceHost = new ServiceHost(c, addresses);

            //<snippet3>
            // Code to create a ServiceHost not shown.
            ServiceAuthorizationBehavior MyServiceAuthoriationBehavior =
                serviceHost.Description.Behaviors.Find <ServiceAuthorizationBehavior>();

            MyServiceAuthoriationBehavior.ImpersonateCallerForAllOperations = true;
            //</snippet3>

            //<snippet4>
            ChannelFactory <IEcho> cf = new ChannelFactory <IEcho>("EchoEndpoint");

            cf.Credentials.Windows.AllowedImpersonationLevel =
                System.Security.Principal.TokenImpersonationLevel.Impersonation;
            //</snippet4>
        }
Exemple #29
0
        public static void Run()
        {
            Uri baseUri = new Uri("http://ServiceModelSamples");

            //<snippet3>
            //<snippet1>
            ServiceHost myServiceHost = new ServiceHost(typeof(Calculator), baseUri);
            ServiceAuthorizationBehavior myServiceBehavior =
                myServiceHost.Description.Behaviors.Find <ServiceAuthorizationBehavior>();

            myServiceBehavior.PrincipalPermissionMode =
                PrincipalPermissionMode.UseAspNetRoles;
            //</snippet1>
            //<snippet5>
            MyServiceAuthorizationManager sm = new MyServiceAuthorizationManager();

            myServiceBehavior.ServiceAuthorizationManager = sm;
            //</snippet5>
            //</snippet3>
            //<snippet11>
            RoleProvider myCustomRoleProvider = myServiceBehavior.RoleProvider;
            //</snippet11>
        }
        private void StartHost()
        {
            try
            {
                object[] permissionAttributes = this.GetType().GetCustomAttributes(typeof(DesktopServiceHostPermissionAttribute), true);
                foreach (DesktopServiceHostPermissionAttribute permissionAttribute in permissionAttributes)
                {
                    if (!PermissionsHelper.IsInRoles(permissionAttribute.AuthorityTokens))
                    {
                        Platform.Log(LogLevel.Warn, "User does not have appropriate permissions to start desktop service ('{0}').", this.GetType().FullName);
                        return;
                    }
                }

                ServiceHost host = CreateServiceHost();

                if (Thread.CurrentPrincipal == null)
                {
                    host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.None;
                }
                else
                {
                    ServiceAuthorizationBehavior sa = host.Description.Behaviors.Find <ServiceAuthorizationBehavior>();
                    sa.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
                    List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();
                    policies.Add(new AuthorizationPolicy(Thread.CurrentPrincipal));
                    host.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly();
                }

                host.Open();
                _host = host;
            }
            catch (Exception e)
            {
                Platform.Log(LogLevel.Debug, e, "Unable to start desktop service; another instance may be running.");
            }
        }