Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Web API security

How can I configure wcf web api service for HTTPS transport? Does anyone know how much this will change in the final release since this is one of the areas they say will change?

like image 703
Darth Avatar asked Feb 22 '26 10:02

Darth


2 Answers

To support HTTPS you will need to enable transport security on the HttpBinding. This can be done by deriving from the HttpConfigurableServiceHostFactory and override the CreateServiceHost like this:

public class HypertextTransferProtocolSecureServiceHostFactory : HttpConfigurableServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        var configurationBuilder = HttpHostConfiguration.Create();

        var host = new HttpConfigurableServiceHost(serviceType, configurationBuilder, baseAddresses);

        foreach (var endpoint in host.Description.Endpoints.Where(e => e.ListenUri.Scheme == "https"))
        {
            var binding = endpoint.Binding as HttpBinding;

            if (binding != null)
            {
                binding.Security.Mode = HttpBindingSecurityMode.Transport;
            }
        }
        return host;
    }
}

Finally the HypertextTransferProtocolSecureServiceHostFactory must be added to the RouteTable:

RouteTable.Routes.Add(new ServiceRoute("routePrefix", new HypertextTransferProtocolSecureServiceHostFactory(), typeof(ServiceType)));
like image 130
hskan Avatar answered Feb 24 '26 17:02

hskan


In our latest drop you can set the binding without creating a new host by using the HttpConfiguration object. It exposes a SetSecurity method you can set to change the security mode.

like image 22
Glenn Block Avatar answered Feb 24 '26 18:02

Glenn Block