Click here to Skip to main content
11,505,486 members (64,029 online)
Click here to Skip to main content

Basic Authentication on a WCF REST Service

, 28 Feb 2011 CPOL 180.7K 8.2K 177
Rate this:
Please Sign up or sign in to vote.
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.

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.

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.

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.

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.

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.

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.

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:

[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)

Share

About the Author

Patrick Kalkman
Architect http://www.hinttech.nl
Netherlands Netherlands
Patrick Kalkman is a senior Software Architect with more than 20 years professional development experience. He works for Hinttech where he develops state of the art web applications.

Patrick enjoys writing his blog. It discusses software architectures using semantic web technologies. Patrick can be reached at pkalkie@gmail.com.

Published Windows 8 apps:

Published Windows Phone apps:

Awards:

Best Mobile article of March 2012
Best Mobile article of June 2012
Follow on   Twitter

Comments and Discussions

 
QuestionHow to call using jQuery ajax? Pin
Member 469425311-Jan-15 17:17
memberMember 469425311-Jan-15 17:17 
QuestionCan we apply this to SOAP services Pin
johnxu208-Aug-14 8:29
memberjohnxu208-Aug-14 8:29 
QuestionThanks! Pin
Member 77200863-Jul-14 1:10
memberMember 77200863-Jul-14 1:10 
AnswerRe: Thanks! Pin
Patrick Kalkman3-Jul-14 1:33
memberPatrick Kalkman3-Jul-14 1:33 
QuestionExcellent article Pin
Member 1062765826-Feb-14 5:17
memberMember 1062765826-Feb-14 5:17 
AnswerRe: Excellent article Pin
Patrick Kalkman26-Feb-14 19:37
memberPatrick Kalkman26-Feb-14 19:37 
QuestionHow to Log in programmatically to the server localhost instead of windows security dialog box? Pin
Member 1001372326-Nov-13 19:41
professionalMember 1001372326-Nov-13 19:41 
QuestionError when used with https and accessing the service from the browser Pin
Lahsiv198113-Mar-13 0:28
memberLahsiv198113-Mar-13 0:28 
GeneralMy vote of 2 Pin
gadasadox8-Jan-13 0:38
membergadasadox8-Jan-13 0:38 
GeneralRe: My vote of 2 Pin
Patrick Kalkman23-Feb-13 21:17
memberPatrick Kalkman23-Feb-13 21:17 
GeneralRe: My vote of 2 Pin
gadasadox17-Jun-13 22:20
membergadasadox17-Jun-13 22:20 
QuestionQuestion about Basic Auth Pin
jim lahey27-Sep-12 3:37
memberjim lahey27-Sep-12 3:37 
AnswerRe: Question about Basic Auth Pin
Patrick Kalkman27-Sep-12 4:08
memberPatrick Kalkman27-Sep-12 4:08 
Question[My vote of 1] A simple client would be nice Pin
msdevtech7-Aug-12 3:45
membermsdevtech7-Aug-12 3:45 
GeneralMy vote of 5 Pin
Hai Qui23-May-12 1:27
memberHai Qui23-May-12 1:27 
GeneralRe: My vote of 5 Pin
Patrick Kalkman5-Aug-12 21:59
memberPatrick Kalkman5-Aug-12 21:59 
Question.Net 4 Pin
JP Barbosa15-Feb-12 14:58
memberJP Barbosa15-Feb-12 14:58 
QuestionWill this work for SOAP Based Service Pin
MuraliVS12-Jan-12 5:08
memberMuraliVS12-Jan-12 5:08 
QuestionHow to disable if we don't want this basic authentication? can we make this enabling/disabling configurable? Pin
MuraliVS9-Jan-12 19:12
memberMuraliVS9-Jan-12 19:12 
AnswerRe: How to disable if we don't want this basic authentication? can we make this enabling/disabling configurable? Pin
Patrick Kalkman10-Jan-12 20:35
memberPatrick Kalkman10-Jan-12 20:35 
QuestionPass credentials from Client application Pin
shrihan016-Nov-11 10:37
membershrihan016-Nov-11 10:37 
AnswerRe: Pass credentials from Client application Pin
Karel Kral29-Dec-11 23:12
memberKarel Kral29-Dec-11 23:12 
GeneralMy vote of 5 Pin
After205018-Oct-11 4:32
memberAfter205018-Oct-11 4:32 
GeneralRe: My vote of 5 Pin
Patrick Kalkman5-Aug-12 22:00
memberPatrick Kalkman5-Aug-12 22:00 
QuestionHow do I make my wcf services available for particular user? Pin
dusshyi330-Sep-11 3:50
memberdusshyi330-Sep-11 3:50 
AnswerRe: How do I make my wcf services available for particular user? Pin
shroin5-Jun-12 11:21
membershroin5-Jun-12 11:21 
Questionstandard security mechanism Pin
sutikshna2-Aug-11 4:11
membersutikshna2-Aug-11 4:11 
AnswerRe: standard security mechanism Pin
Patrick Kalkman14-Aug-11 1:01
memberPatrick Kalkman14-Aug-11 1:01 
GeneralProblem with Self-Host Pin
Member 27984678-Apr-11 13:04
memberMember 27984678-Apr-11 13:04 
GeneralRe: Problem with Self-Host Pin
Patrick Kalkman9-Apr-11 19:20
memberPatrick Kalkman9-Apr-11 19:20 
GeneralRe: Problem with Self-Host Pin
BrianCHenry10-Apr-11 7:07
memberBrianCHenry10-Apr-11 7:07 
GeneralRe: Problem with Self-Host Pin
masti525-Oct-11 5:49
membermasti525-Oct-11 5:49 
GeneralRe: Problem with Self-Host Pin
Setiri16-Oct-11 11:40
memberSetiri16-Oct-11 11:40 
GeneralRe: Problem with Self-Host Pin
cansik28-Oct-11 0:56
membercansik28-Oct-11 0:56 
GeneralRe: Problem with Self-Host Pin
jeremylei30-Nov-11 10:04
memberjeremylei30-Nov-11 10:04 
GeneralRe: Problem with Self-Host Pin
jeremylei30-Nov-11 10:04
memberjeremylei30-Nov-11 10:04 
GeneralRe: Problem with Self-Host Pin
jeremylei30-Nov-11 10:03
memberjeremylei30-Nov-11 10:03 
GeneralRe: Problem with Self-Host Pin
jeremylei30-Nov-11 10:03
memberjeremylei30-Nov-11 10:03 
GeneralRe: Problem with Self-Host Pin
jeremylei30-Nov-11 10:02
memberjeremylei30-Nov-11 10:02 
GeneralMy vote of 5 Pin
Monjurul Habib2-Apr-11 10:45
memberMonjurul Habib2-Apr-11 10:45 
GeneralRe: My vote of 5 Pin
Patrick Kalkman5-Apr-11 1:31
memberPatrick Kalkman5-Apr-11 1:31 
QuestionA question Pin
pareshsofty14-Mar-11 17:44
memberpareshsofty14-Mar-11 17:44 
AnswerRe: A question Pin
Patrick Kalkman14-Mar-11 22:33
memberPatrick Kalkman14-Mar-11 22:33 
QuestionGreat article, any thoughts on WCF 4? Pin
Kai Friis1-Mar-11 21:06
memberKai Friis1-Mar-11 21:06 
AnswerRe: Great article, any thoughts on WCF 4? Pin
Patrick Kalkman2-Mar-11 11:34
memberPatrick Kalkman2-Mar-11 11:34 
GeneralI figured it out [modified] Pin
Kai Friis2-Mar-11 20:05
memberKai Friis2-Mar-11 20:05 
QuestionIIS error Pin
winy1011-Mar-11 11:08
memberwiny1011-Mar-11 11:08 
AnswerRe: IIS error Pin
Patrick Kalkman2-Mar-11 11:30
memberPatrick Kalkman2-Mar-11 11:30 
QuestionCan we do it without REST starter kit? Pin
mandarpkulkarni@gmail.com1-Mar-11 2:27
membermandarpkulkarni@gmail.com1-Mar-11 2:27 
AnswerRe: Can we do it without REST starter kit? Pin
Patrick Kalkman1-Mar-11 8:28
memberPatrick Kalkman1-Mar-11 8:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 28 Feb 2011
Article Copyright 2011 by Patrick Kalkman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid