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:
Conclusion: As like normal WCF services, WCF REST base services can also be easily configured for security.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades 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), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn