Click here to Skip to main content
15,867,141 members
Articles / Security / Encryption

Basic Authentication on a WCF REST Service

Rate me:
Please Sign up or sign in to vote.
4.89/5 (46 votes)
28 Feb 2011CPOL6 min read 345.2K   10.8K   191   74
An assembly that adds Basic Authentication to an IIS hosted WCF REST service to validate against any back-end.

Contents

Introduction

This article explains a method to secure a REST based service using Basic Authentication. The service itself is implemented using Microsoft Windows Communication Foundation. The authentication of the credentials should be possible against any type of backend. For example, authenticate against an Active Directory, a custom file, or a database. Basic Authentication is a standard available in combination with WCF and IIS, but the downside of this is that authentication is only possible against an Active Directory.

Although Basic Authentication is a method to secure a web site or service, the authentication mechanism itself is not secure. The user name and password are sent Base64 encoded over the internet. To make this more secure, the server should offer the service using HTTPS. HTTPS secures the channel so that the Base64 encoded user name and password cannot be decrypted. An alternative to Basic Authentication is Digest Authentication which is also possible with WCF REST. I created a separate article on CodeProject that describes Digest Authentication on a WCF REST Service.

This article and the provided source code can be used in two ways. First, just download the code, go down to the Using the code section, and implement your WCF service using Basic Authentication. Second, you can use the article to learn what exactly is Basic Authentication and how can WCF REST be extended.

Basic Authentication

Basic Authentication is a standard protocol defined within HTTP 1.0 that defines an authentication scheme. In this scheme, the client must authenticate itself with a user-ID and password. Basic Authentication is described in RFC 2617. When a client requests a resource from a site that is protected using Basic Authentication, the server returns a 401 "Not authorized" response. Inside this response, the server has added an indication that the site is protected using Basic Authentication. The server adds WWW-Authenticate: Basic realm="site" to the header of the response; Basic indicates that the authentication scheme is Basic Authentication, and realm is a string that indicates which part of the site is protected. It has no further usage in the actual authentication mechanism itself. An internet browser generates a dialog based on this response message. This dialog shows the realm and allows a user to enter a user name and password.

Image 1

Image 2

When a user enters the user name and password, the client resends the request but adds "Authorization: Basic SGVsbG8gQmFzZTY0" to the header of the request. The characters after Basic are the user name and password, separated by a single colon ":" in a Base64 encoded string. The server decodes the string, extracts the credentials, and validates them against the back-end. When the credentials are correctly validated, the server returns the requested content to the client.

Image 3

Extending WCF REST

To be able to integrate Basic Authentication with WCF REST, we have to extend the functionality of the WCF framework. The extension is divided into three steps:

  • Find the extension point to apply behavior to all operations of the service
  • Create a custom authentication mechanism based on existing standards
  • Create a security context based on the given credentials

Each of these steps is described in this article.

Finding the extension point, RequestInterceptor

WCF REST is part of the WCF REST Starter Kit. Unlike standard WCF, the WCF Starter Kit provides a simple way to apply the behaviour to all server operations. Adding this behavior to normal WCF can get fairly complex. WCF REST uses Request Interceptors. Request Interceptors shield you from the more complex extensibility points. Request Interceptors are executed at the WCF channel level, and enable you to interpret the incoming request and generate an appropriate response.

C#
public class MyRequestInterceptor : RequestInterceptor
{
   public override void ProcessRequest(ref RequestContext requestContext)
   {
      //Access request with requextContext.RequestMessage
   }
}

By deriving a new class from the RequestInterceptor base class, you create a custom request interceptor. The method ProcessRequest is executed for every request that arrives at the service. Inside this method, you can read the header of the request and decode the Base64 encoded string if it is present. If it is not present, a response is generated that includes WWW-Authenticate: Basic realm="site" in the header. If it is present, we create a new security context and set the credentials on this context.

Linking the custom RequestInterceptor to the service

The RequestInterceptor can be linked to the service by creating a custom ServiceHostFactory. The ServiceHostFactory is responsible for providing instances of ServiceHost in managed hosting environments. By managed hosting environments I mean services that are hosted within IIS. The CreateServiceHost method of the ServiceHostFactory creates a new WebServiceHost and adds the new RequestInceptor to the Interceptors collection.

C#
public class BasicAuthenticationHostFactory : ServiceHostFactory
{
   protected override ServiceHost CreateServiceHost(Type serviceType, 
                                  Uri[] baseAddresses)
   {
      var serviceHost = new WebServiceHost2(serviceType, true, baseAddresses);
      serviceHost.Interceptors.Add(RequestInterceptorFactory.Create(
                    "DataWebService", new CustomMembershipProvider()));
      return serviceHost;
   }
}

This new ServiceHostFactory is linked to the service through the markup file (.svc) of the service. Inside the markup, you add the host factory of the service.

XML
Factory="WCFServer.BasicAuthenticationHostFactory"

Custom authentication method, creating a custom MembershipProvider

The provided source code uses a MembershipProvider to actually perform the authentication of the credentials of the client. You can write your own membership provider by deriving from MembershipProvider. The only method that needs to be implemented is the ValidateUser method. This is the method the code uses to validate the user. This custom MembershipProvider is linked to the RequestInterceptor in the CreateServiceHost method of the ServiceHostFactory.

C#
public class CustomMembershipProvider : MembershipProvider
{
   public override bool ValidateUser(string username, string password)
   {
      //perform validation
      return false;
   }

   .....
}

Creating a security context

After we have authenticated the incoming request, we have to create and set the security context. This enables the usage of the client credentials inside a service method. WCF uses the thread local ServiceSecurityContext for this. After the request has been authenticated, a new ServiceSecurityContext is created and added to the incoming request. See the code below from the provided source code that creates a new ServiceSecurityContext.

C#
internal ServiceSecurityContext Create(Credentials credentials)
{
   var authorizationPolicies = new List<iauthorizationpolicy>();
   authorizationPolicies.Add(authorizationPolicyFactory.Create(credentials));
   return new ServiceSecurityContext(authorizationPolicies.AsReadOnly());
}

This enables to retrieve the user name of a service method as follows:

C#
[OperationContract]
public string DoWork()
{
   string name = ServiceSecurityContext.Current.PrimaryIdentity.Name;
   return "Hello " + name;
}

Using the code

If you want to secure your own WCF REST service with Basic Authentication using the provided source code, you need to execute the following steps:

  • Add a reference to the BasicAuthenticationUsingWCF assembly
  • Create a new Membership Provider derived from MembershipProvider
  • Implement the ValidateUser method against your back-end security storage
  • Create a custom BasicAuthenticationHostFactory, see the example in the provided source code
  • Add the new BasciAuthenticationHostFactory to the markup of the .svc file

Points of interest

Although Basic Authentication is a method to secure a web site or service, the authentication mechanism itself is not secure. The user name and password are sent Base64 encoded over the internet. To make this more secure, the server should offer the service using HTTPS. HTTPS secures the channel so that the Base64 encoded user name and password cannot be decrypted.

Basic Authentication in combination with HTTPS is used frequently when you want to offer your service to third parties and provide easy interoperable service. If however you control both side of the wire, client and server, WCF offers a standard security mechanism that can be added to your service using configuration.

This article and source code is based on the example of Pablo M. Cibraro who deserves the credits for the solution.

The provided source code is developed using TDD, and uses the NUnit framework for creating and executing tests. Rhino Mocks is used as a mocking framework inside the unit tests.

History

  • 23 Jan., 2011
    • Initial post and first version.
  • 28 Feb., 2011

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect http://www.simpletechture.nl
Netherlands Netherlands
Patrick Kalkman is a senior Software Architect with more than 20 years professional development experience. He works for SimpleTechture where he helps teams develop state of the art web applications.

Patrick enjoys writing his blog. It discusses agile software development. Patrick can be reached at patrick@simpletechture.nl.

Published Windows 8 apps:


Published Windows Phone apps:


Awards:

Best Mobile article of March 2012
Best Mobile article of June 2012

Comments and Discussions

 
QuestionCan we do it without REST starter kit? Pin
mandarpkulkarni@gmail.com1-Mar-11 2:27
mandarpkulkarni@gmail.com1-Mar-11 2:27 
AnswerRe: Can we do it without REST starter kit? Pin
Patrick Kalkman1-Mar-11 8:28
Patrick Kalkman1-Mar-11 8:28 
GeneralRe: Can we do it without REST starter kit? Pin
mandarpkulkarni@gmail.com2-Mar-11 23:10
mandarpkulkarni@gmail.com2-Mar-11 23:10 
GeneralRe: Can we do it without REST starter kit? Pin
BrianCHenry10-Apr-11 7:13
BrianCHenry10-Apr-11 7:13 
GeneralMy vote of 5 Pin
maq_rohit28-Feb-11 19:38
professionalmaq_rohit28-Feb-11 19:38 
GeneralRe: My vote of 5 Pin
Patrick Kalkman1-Mar-11 8:18
Patrick Kalkman1-Mar-11 8:18 
GeneralMy vote of 5 Pin
Tawani Anyangwe23-Feb-11 8:55
Tawani Anyangwe23-Feb-11 8:55 
GeneralRe: My vote of 5 Pin
Patrick Kalkman27-Feb-11 23:58
Patrick Kalkman27-Feb-11 23:58 
GeneralSuggestion Pin
Gebbetje31-Jan-11 22:07
Gebbetje31-Jan-11 22:07 
GeneralRe: Suggestion Pin
Patrick Kalkman31-Jan-11 23:43
Patrick Kalkman31-Jan-11 23:43 
GeneralMy vote of 5 Pin
pietvredeveld26-Jan-11 20:43
pietvredeveld26-Jan-11 20:43 
GeneralRe: My vote of 5 Pin
Patrick Kalkman29-Jan-11 19:59
Patrick Kalkman29-Jan-11 19:59 
GeneralMy Vote of 5 Pin
RaviRanjanKr25-Jan-11 17:42
professionalRaviRanjanKr25-Jan-11 17:42 
GeneralRe: My Vote of 5 Pin
Patrick Kalkman29-Jan-11 19:58
Patrick Kalkman29-Jan-11 19:58 
GeneralGood article, 5 from me Pin
Sacha Barber24-Jan-11 21:53
Sacha Barber24-Jan-11 21:53 
GeneralRe: Good article, 5 from me Pin
Patrick Kalkman29-Jan-11 19:58
Patrick Kalkman29-Jan-11 19:58 
GeneralMy Vote of 5 Pin
Don Kackman24-Jan-11 2:16
Don Kackman24-Jan-11 2:16 
GeneralRe: My Vote of 5 Pin
Patrick Kalkman29-Jan-11 19:58
Patrick Kalkman29-Jan-11 19:58 
GeneralMy vote of 5 Pin
Nicholas Butler24-Jan-11 1:54
sitebuilderNicholas Butler24-Jan-11 1:54 
GeneralRe: My vote of 5 Pin
Patrick Kalkman29-Jan-11 19:58
Patrick Kalkman29-Jan-11 19:58 
GeneralMy vote of 5 Pin
Kanasz Robert24-Jan-11 1:05
professionalKanasz Robert24-Jan-11 1:05 
GeneralRe: My vote of 5 Pin
Patrick Kalkman29-Jan-11 19:58
Patrick Kalkman29-Jan-11 19:58 
Generalthanks for sharing - have 5 Pin
Pranay Rana24-Jan-11 0:52
professionalPranay Rana24-Jan-11 0:52 
GeneralRe: thanks for sharing - have 5 Pin
Patrick Kalkman29-Jan-11 19:57
Patrick Kalkman29-Jan-11 19:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.