public void Validate () { var b = new ServiceAuthorizationBehavior (); IServiceBehavior sb = b; sb.Validate (new ServiceDescription (), new ServiceHost (typeof (object))); }
private ServiceAuthorizationBehavior(ServiceAuthorizationBehavior other) { this.impersonateCallerForAllOperations = other.impersonateCallerForAllOperations; this.principalPermissionMode = other.principalPermissionMode; this.roleProvider = other.roleProvider; this.isExternalPoliciesSet = other.isExternalPoliciesSet; this.isAuthorizationManagerSet = other.isAuthorizationManagerSet; if (other.isExternalPoliciesSet || other.isAuthorizationManagerSet) { this.CopyAuthorizationPoliciesAndManager(other); } this.isReadOnly = other.isReadOnly; }
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"); }
protected internal override object CreateBehavior() { ServiceAuthorizationBehavior behavior = new ServiceAuthorizationBehavior { 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(System.ServiceModel.SR.GetString("InvalidRoleProviderSpecifiedInConfig", new object[] { roleProviderName }))); } } behavior.ImpersonateCallerForAllOperations = this.ImpersonateCallerForAllOperations; string serviceAuthorizationManagerType = this.ServiceAuthorizationManagerType; if (!string.IsNullOrEmpty(serviceAuthorizationManagerType)) { Type c = Type.GetType(serviceAuthorizationManagerType, true); if (!typeof(ServiceAuthorizationManager).IsAssignableFrom(c)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("ConfigInvalidServiceAuthorizationManagerType", new object[] { serviceAuthorizationManagerType, typeof(ServiceAuthorizationManager) }))); } behavior.ServiceAuthorizationManager = (ServiceAuthorizationManager) Activator.CreateInstance(c); } AuthorizationPolicyTypeElementCollection authorizationPolicies = this.AuthorizationPolicies; if (authorizationPolicies.Count > 0) { List<IAuthorizationPolicy> list = 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(System.ServiceModel.SR.GetString("ConfigInvalidAuthorizationPolicyType", new object[] { authorizationPolicies[i].PolicyType, typeof(IAuthorizationPolicy) }))); } list.Add((IAuthorizationPolicy) Activator.CreateInstance(type)); } behavior.ExternalAuthorizationPolicies = list.AsReadOnly(); } return behavior; }
/// <summary> /// Initializes the <see cref="ServiceHost"/>. /// </summary> protected virtual void InitializeServiceHost() { if (m_serviceEnabled && !string.IsNullOrEmpty(m_endpoints)) { // Initialize service host. string serviceUri = GetServiceAddress(); if (m_singleton) m_serviceHost = new ServiceHost(this, new Uri(serviceUri)); else m_serviceHost = new ServiceHost(this.GetType(), new Uri(serviceUri)); // Enable metadata publishing. if (m_publishMetadata) { ServiceMetadataBehavior serviceBehavior = m_serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>(); if ((object)serviceBehavior == null) { serviceBehavior = new ServiceMetadataBehavior(); m_serviceHost.Description.Behaviors.Add(serviceBehavior); } serviceBehavior.HttpGetEnabled = true; } // Enable security on the service. if (!string.IsNullOrEmpty(m_securityPolicy)) { ServiceAuthorizationBehavior serviceBehavior = m_serviceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); if ((object)serviceBehavior == null) { serviceBehavior = new ServiceAuthorizationBehavior(); m_serviceHost.Description.Behaviors.Add(serviceBehavior); } serviceBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom; List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(); Type securityPolicyType = Type.GetType(m_securityPolicy); if ((object)securityPolicyType == null) throw new NullReferenceException(string.Format("Failed get security policy type '{0}' for self-hosting service - check config file settings.", m_securityPolicy.ToNonNullNorWhiteSpace("[undefined]"))); policies.Add((IAuthorizationPolicy)Activator.CreateInstance(securityPolicyType)); serviceBehavior.ExternalAuthorizationPolicies = policies.AsReadOnly(); } // Add specified service endpoints. string serviceAddress; string[] serviceAddresses; Binding serviceBinding; ServiceEndpoint serviceEndpoint; serviceAddresses = m_endpoints.Split(';'); // Enable Windows Authentication if authorization policy is configured. if (!string.IsNullOrEmpty(m_securityPolicy)) m_windowsAuthentication = true; for (int i = 0; i < serviceAddresses.Length; i++) { serviceAddress = serviceAddresses[i].Trim(); serviceBinding = Service.CreateServiceBinding(ref serviceAddress, m_windowsAuthentication); if ((object)serviceBinding == null) continue; Type contractInterfaceType = Type.GetType(m_contractInterface); if ((object)contractInterfaceType == null) throw new NullReferenceException(string.Format("Failed to get contract interface type '{0}' for self-hosting service - check config file settings.", m_contractInterface.ToNonNullNorWhiteSpace("[undefined]"))); serviceEndpoint = m_serviceHost.AddServiceEndpoint(contractInterfaceType, serviceBinding, serviceAddress); if (serviceBinding is WebHttpBinding) { // Special handling for REST endpoint. WebHttpBehavior restBehavior = new WebHttpBehavior(); #if !MONO if (m_publishMetadata) restBehavior.HelpEnabled = true; #endif serviceEndpoint.Behaviors.Add(restBehavior); } else if (m_publishMetadata) { // Add endpoint for service metadata. if (serviceAddress.StartsWith("http://")) m_serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), serviceAddress + "/mex"); else if (serviceAddress.StartsWith("net.tcp://")) m_serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), serviceAddress + "/mex"); else if (serviceAddress.StartsWith("net.pipe://")) m_serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexNamedPipeBinding(), serviceAddress + "/mex"); } } // Enable cross domain access. if (m_allowCrossDomainAccess) m_serviceHost.AddServiceEndpoint(typeof(IPolicyRetriever), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); // Allow for customization. OnServiceHostCreated(); // Start the service. m_serviceHost.Open(); OnServiceHostStarted(); } }
protected internal override object CreateBehavior () { var b = new ServiceAuthorizationBehavior (); if (!String.IsNullOrEmpty (ServiceAuthorizationManagerType)) b.ServiceAuthorizationManager = (ServiceAuthorizationManager) Activator.CreateInstance (ConfigUtil.GetTypeFromConfigString (ServiceAuthorizationManagerType, NamedConfigCategory.None)); foreach (var apte in AuthorizationPolicies) throw new NotImplementedException (); if (!String.IsNullOrEmpty (RoleProviderName)) throw new NotImplementedException (); b.ImpersonateCallerForAllOperations = ImpersonateCallerForAllOperations; b.PrincipalPermissionMode = PrincipalPermissionMode; return b; }
private void CopyAuthorizationPoliciesAndManager(ServiceAuthorizationBehavior other) { this.externalAuthorizationPolicies = other.externalAuthorizationPolicies; this.serviceAuthorizationManager = other.serviceAuthorizationManager; }
void CopyAuthorizationPoliciesAndManager(ServiceAuthorizationBehavior other) { this.externalAuthorizationPolicies = other.externalAuthorizationPolicies; this.serviceAuthorizationManager = other.serviceAuthorizationManager; }
/// <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; }
private void SecureRestService_ServiceHostCreated(object sender, EventArgs e) { // Enable windows authentication for all defined service endpoints. foreach (ServiceEndpoint serviceEndpoint in ServiceHost.Description.Endpoints) { WebHttpBinding binding = serviceEndpoint.Binding as WebHttpBinding; if (binding != null) { binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; } } // Specify custom security policy to enforce role-based security. ServiceAuthorizationBehavior serviceBehavior = ServiceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); if (serviceBehavior == null) { serviceBehavior = new ServiceAuthorizationBehavior(); ServiceHost.Description.Behaviors.Add(serviceBehavior); } serviceBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom; List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(); policies.Add(new SecurityPolicy()); serviceBehavior.ExternalAuthorizationPolicies = policies.AsReadOnly(); }
protected static void SetupServiceAuthorization(ServiceHost host) { var policies = ServiceLocator.GetAllInstances<IAuthorizationPolicy>().ToArray(); if (policies.Length == 0) _Log.Warn("No authorization policies are in place."); var authBehavior = host.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); if (authBehavior == null) { authBehavior = new ServiceAuthorizationBehavior(); host.Description.Behaviors.Add(authBehavior); } authBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom; host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom; authBehavior.ServiceAuthorizationManager = new Security.ServiceAuthorizationManager(); authBehavior.ExternalAuthorizationPolicies = new ReadOnlyCollection<IAuthorizationPolicy>(policies); _Log.DebugFormat("{0} IAuthorizationPolicy found and configured", policies.Length); }
/// <summary> /// Creates a new <see cref="ServiceHost"/> 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="ServiceHost"/>.</returns> protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { #if MONO throw new NotSupportedException("Not supported under Mono."); #else // Check security requirement. bool integratedSecurity = (Service.GetAuthenticationSchemes(baseAddresses[0]) & AuthenticationSchemes.Anonymous) != AuthenticationSchemes.Anonymous; // Create service host. ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses); // Enable meta-data publishing. if (m_publishMetadata) { ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); if (metadataBehavior == null) { metadataBehavior = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(metadataBehavior); } metadataBehavior.HttpGetEnabled = true; } // Enable security on the service. if (!m_disableSecurity) { ServiceAuthorizationBehavior authorizationBehavior = host.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); if (authorizationBehavior == null) { authorizationBehavior = new ServiceAuthorizationBehavior(); host.Description.Behaviors.Add(authorizationBehavior); } authorizationBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom; List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(); policies.Add((IAuthorizationPolicy)Activator.CreateInstance(m_authorizationPolicy)); authorizationBehavior.ExternalAuthorizationPolicies = policies.AsReadOnly(); } // Create endpoint and configure security. (Not supported on Mono) host.AddDefaultEndpoints(); if (string.IsNullOrEmpty(m_protocol)) { // Use the default endpoint. foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { BasicHttpBinding basicBinding = endpoint.Binding as BasicHttpBinding; if (basicBinding != null) { // Default endpoint uses BasicHttpBinding. if (integratedSecurity) { // Enable security. basicBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; basicBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; } else { // Disable security. basicBinding.Security.Mode = BasicHttpSecurityMode.None; basicBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; } foreach(IEndpointBehavior behavior in m_endpointBehaviors ?? new List<IEndpointBehavior>()) { endpoint.Behaviors.Add(behavior); } } } } else { // Create endpoint using the specifics. host.Description.Endpoints.Clear(); Binding serviceBinding; ServiceEndpoint serviceEndpoint; serviceBinding = Service.CreateServiceBinding(ref m_protocol, integratedSecurity); if (serviceBinding != null) { // Binding created for the endpoint. Type contract = Service.GetServiceContract(serviceType); if (!string.IsNullOrEmpty(m_address)) serviceEndpoint = host.AddServiceEndpoint(contract, serviceBinding, m_address); else serviceEndpoint = host.AddServiceEndpoint(contract, serviceBinding, string.Empty); // Special handling for REST endpoint. if (serviceBinding is WebHttpBinding) { WebHttpBehavior restBehavior = new WebHttpBehavior(); //#if !MONO if (m_publishMetadata) restBehavior.HelpEnabled = true; //#endif serviceEndpoint.Behaviors.Add(restBehavior); serviceEndpoint.Behaviors.Add(new FormatSpecificationBehavior()); } foreach (IEndpointBehavior behavior in m_endpointBehaviors ?? new List<IEndpointBehavior>()) { serviceEndpoint.Behaviors.Add(behavior); } } } foreach(var behavior in ServiceBehaviors ?? new List<IServiceBehavior>()) { host.Description.Behaviors.Add(behavior); } return host; #endif }