Securing WCF REST Service using Windows Authentication

Posted by: Mahesh Sabnis , on 12/20/2009, in Category Windows Communication Foundation (WCF)
Views: 55384
Abstract: This article demonstrates that like normal WCF services, WCF REST base services can also be easily configured for security.
There are lots of articles and other resources available on WCF security. However recently one of my clients put across a requirement where WCF REST service was used in an application but before the data could be fetched from the REST URL, he wanted to pass the windows credentials and authenticate the user. The client was using a Windows application. I took this thought ahead and came up with a solution that I will be sharing through this article
The WCF service created with below interface and Web.Config:
Interface:
C#
[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet]
    string GetData(int value);
}
VB.NET
<ServiceContract> _
Public Interface IService1
      <OperationContract, WebGet> _
      Function GetData(ByVal value As Integer) As String
End Interface
Web.Config:
 <system.serviceModel>
    <services>
      <servicename="WCF_REST_UserNamePassword.Service1"
               behaviorConfiguration="WCF_REST_UserNamePassword.Service1Behavior">
        <endpointaddress=""binding="webHttpBinding"
                  contract="WCF_REST_UserNamePassword.IService1"
                    bindingConfiguration="wbBind">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behaviorname="WCF_REST_UserNamePassword.Service1Behavior">
          <serviceMetadatahttpGetEnabled="true"/>
          <serviceDebugincludeExceptionDetailInFaults="false"/>
          <serviceCredentials>
            <windowsAuthenticationallowAnonymousLogons="False"includeWindowsGroups="True"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <bindingname="wbBind">
          <securitymode="TransportCredentialOnly">
            <transportclientCredentialType="Windows"proxyCredentialType="Windows"/>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
 </system.serviceModel>
 
The ‘webHttpBinding’ uses security mode as ‘TransportWithCredential’ and uses ‘ClientCredentialType=Windows’. The Service behavior denies anonymous logon access.
To test this service, I have published it with IIS 7.0 and then tried to browse “Service.Svc”. It asks for the windows credential.
The console client application defined makes call to WCF REST service as shown below:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.Runtime.Serialization;
 
namespace Conole_REST_Client
{
    class Program
    {
        static void Main(string[] args)
        {
 
            var val = 100;
            Uri reqUri = new Uri("http://localhost/REST_Security/Service1.svc/GetData?value=" + val);
 
            Console.WriteLine("Enter USer Name");
            string userName = Console.ReadLine();
 
            Console.WriteLine("Entered Password");
            string password = Console.ReadLine();
 
            WebRequest req = WebRequest.Create(reqUri);
 
            req.PreAuthenticate = true;
 
            NetworkCredential credential = new NetworkCredential(userName, password);
 
            req.Credentials = credential;
 
            WebResponse resp = req.GetResponse();
 
 
            DataContractSerializer data = new DataContractSerializer(typeof(string));
            var res = data.ReadObject(resp.GetResponseStream());
 
            Console.WriteLine(res);
 
            Console.ReadLine();
        }
    }
}
 
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Xml
Imports System.Net
Imports System.Runtime.Serialization
 
Namespace Conole_REST_Client
      Friend Class Program
            Shared Sub Main(ByVal args() As String)
 
                  Dim val = 100
                  Dim reqUri As New Uri("http://localhost/REST_Security/Service1.svc/GetData?value=" & val)
 
                  Console.WriteLine("Enter USer Name")
                  Dim userName As String = Console.ReadLine()
 
                  Console.WriteLine("Entered Password")
                  Dim password As String = Console.ReadLine()
 
                  Dim req As WebRequest = WebRequest.Create(reqUri)
 
                  req.PreAuthenticate = True
 
                  Dim credential As New NetworkCredential(userName, password)
 
                  req.Credentials = credential
 
                  Dim resp As WebResponse = req.GetResponse()
 
 
                  Dim data As New DataContractSerializer(GetType(String))
                  Dim res = data.ReadObject(resp.GetResponseStream())
 
                  Console.WriteLine(res)
 
                  Console.ReadLine()
            End Sub
      End Class
End Namespace
 
The NetworkCredential class is used to define client credentials and the important point here is that the ‘PreAuthenticate’ property of the WebRequest class is set to ‘true’. This indicates that credential information will be sent when the client makes a request to the service. The NetworkCredential object is passed to the ‘Credential’ property of the ‘WebRequestClass’.
After running the application the output will be displayed as below:
Output

Conclusion: As like normal WCF services, WCF REST base services can also be easily configured for security.

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Mahesh is having 10 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Piyush on Monday, December 21, 2009 1:48 AM
Very useful info
Comment posted by Ravi Ramchandani on Tuesday, August 31, 2010 4:36 AM
Thanks for this helpful article.

Basically I want to ask if this is applicable to WCF REST 4.0 in II 7.0 since their is no .svc file in .NET 4.0 REST.
Your inputs would be greatly appreciated
Thank you

Regards,
Ravi
Comment posted by Naftali on Thursday, January 23, 2014 6:48 AM
Hi,
thanks for the clear article.
still I have some issue with it.
I have an exception while I'm trying it.
Cannot add the 'serviceCredentials' behavior extension to 'REST' endpoint behavior because the underlying behavior type does not implement the IEndpointBehavior interface

what can solve it?
I can't see the C# code for behavior class. it's there or I can do it without it?

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel