Sunday, 26 May 2013

Creating a WCF ServiceBehavior to enforce HTTPS

The following code will enforce your WCF Services to use HTTPS:

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace TestHttpsRequiredServiceBehavior
{

    public class RequireHttpsServiceBehavior : Attribute, IServiceBehavior
    {

        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (var se in serviceDescription.Endpoints)
            {
                if (string.Compare(se.Binding.Scheme, "https", true) != 0)
                    throw new FaultException("This service requires HTTPS!");
            }
        }

    }
}

The WCF services you can create can then apply this WCF ServiceBehavior using an attribute on the WCF Service implementation class:

  [RequireHttpsServiceBehavior]
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
..

Of course, you have to enable HTTPS also on your machine and set up your Visual Studio solution consuming the WCF service to use HTTPS.

No comments:

Post a Comment