Wednesday, 21 October 2015

Securing WCF REST API using SSL and Basic Authentication

A complete guide to create secure WCF REST API with custom Basic Authentication

WCF REST API services are still being used by many developers for client server connectivity for data and messaging. This blog is a complete guide on creating a WCF Rest service from scratch and Adding security to the service using Basic Authentication. Then we’ll learn how to encrypt the basic authentication information which would be sent over the network using SSL. The main sections of this guide are:

Pre-requisite:

  • Basic knowledge of Visual studio/WCF basics.
  • Visual studio version > 2008
  • .Net framework > 3.5 installed
  • IIS server >7 or equal

Creating a WCF REST API service

To get started quickly we’ll be using the default template of WCF service library provided in Visual studio 2013 which I’m going to use in this guide. Follow the steps below:

1. Launch visual studio 2013(choose “Run as Administrator”, we’ll see later why?)
2. From Menu File -> New -> Project. or click on Start Page to start a New Project. clip_image002
3. Let’s name it as WcfWebHttpIISHostingSample Now you’ll see couple of files already added to the Wcf Service project.
clip_image003 
4. Delete IService1.cs and Service1.svc file as we’ll be creating new files and use our code to host the service via ServiceHostFactory class.

5. Add a new interface ITestService by right click on project and Add new item -> select Interface and rename it to ITestService. Copy below code and add it in newly created interface.

namespace WcfWebHttpIISHostingSample
{
[ServiceContract]
public interface ITestService
{
[WebInvoke(Method = "GET", UriTemplate = "/Data/{data}")]
string GetData(string data);
}
}
In above interface we have added WebInvoke attribute though we can also use WebGet it would not make any difference. I’ll stick with WebInvoke as it support POST, PUT, DELETE http verbs as well.

6. Add a new class TestService which will implement the above declared interface.

using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;

namespace WcfWebHttpIISHostingSample
{
[ServiceContract]
public interface ITestService
{
[WebInvoke(Method = "GET", UriTemplate = "/Data/{data}")]
string GetData(string data);
}
}
7. We have defined a service contract, a Rest method with a sample definition. Now we have to define its end points. To add end point simply copy below settings and paste it into your configuration file(web.config) of newly created project file under service.model tag.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpServiceBehavior">
<!-- Important this is the behavior that makes a normal WCF service to REST based service-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WcfWebHttpIISHostingSample.TestService" behaviorConfiguration="ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost/WCFRestAuthentication/api/"/>
</baseAddresses>
</host>
<endpoint binding="webHttpBinding" contract="WcfWebHttpIISHostingSample.ITestService" behaviorConfiguration="webHttpServiceBehavior"/>
</service>
</services>
</system.serviceModel>
8. Now we have an end point. So Next we’ll add a service host factory that will host the service in IISExpress or Local development server at this moment.

9. Add new item Global.asax and add following code in Application_Start method. You can find it Under New Item -> Web -> Global application Handler.

protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(TestService)));
}
10. Now you’ll be getting an error on ServiceRoute class in above code. To remove this error we have to add a new reference from Add reference -> Assemblies -> System.Model.Activation. And the error will be gone.
11. Now right click on Project and go to Properties. In properties window select Web and Add specific page details to map the service operation that we defined on our contract. Add Data/HelloWorldTestData in Specific page setting. Here Data is your path of operation that we have defined in WebInvoke attribute and “HelloWorldTestData” is your argument that the service method will receive as argument. See below:

clip_image004

12. Save All and Press F5.

clip_image006 
If you see a web page like this means you have successfully created a WCF REST service.

Continue to - Hosting and Deploying a WCF REST service in IIS
Download the complete tutorial Guide as PDF from here.