Technology Corner

Home » DotNet » Implement windows authentication and security in WCF Service

Implement windows authentication and security in WCF Service

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates


RSS InfoQ Feeds

  • First Pedestrian Killed by Self-Driving Car
    A pedestrian was killed on Sunday evening in Tempe, Arizona by a self-driving car operated by Uber, the BBC reports. The firm confirmed that the vehicle was traveling in autonomous mode with a safety driver, the only vehicle occupant, behind the wheel during the crash. By Roland Meertens
  • Microsoft Embeds Artificial Intelligence in Windows 10 Update
    The next Windows 10 update opens the way for the integration of artificial intelligence functionalities within Windows applications. Developers will be able to integrate pre-trained deep-learning models converted to the ONNX framework in their Windows applications. By Alexis Perrier
  • Ankyra Presents “Escape”, a Release Automation Tool that Manages Platforms as Logical Components
    Over the last ten years there has been increased focus on infrastructure as code (IaC) tooling, primarily driven by the rise of Infrastructure as a Service (IaaS) and API-driven infrastructure. InfoQ discussed the challenges of homogenising this tooling with Bart Spaans, founder of Ankyra, who is an expert in the domain of infrastructure and release engineer […]
  • Article: Servlet and Reactive Stacks in Spring Framework 5
    Spring Framework 5 supports both traditional servlet-based and reactive web stacks, in the same server application, reflecting a major shift towards asynchronous, non-blocking concurrency in applications. In this article Spring committer Rossen Stoyanchev explores and contrasts both stacks, and explains the range of available choices, and provides guidance f […]
  • Presentation: Elm and Game Development, a Perfect Fit
    Paulo Diniz discusses the Elm architecture, how to use it as functional reactive programming for web game development. By Paulo Diniz
  • Google Releases “Skaffold”, a Tool That Facilitates Continuous Development with Kubernetes
    Google has released Skaffold, an open source command line tool that facilitates continuous development for Kubernetes applications. Skaffold is entering an increasingly crowded space of Kubernetes development automation tooling, including Azure’s Draft, Datawire’s Forge and Weavework’s Flux. By Daniel Bryant
  • Q&A with Marisa Fagen on Security Championship
    Security lead Marisa Fagen recently spoke at QConLondon 2018 about upskilling and elevating engineering team members into the role of Security Champions. We catch up with Fagen and report on her efforts to address contention caused by a scarcity of security professionals. By Rafiq Gemmail
  • GitHub Licensed Aims to Make it Easier to Comply with OSS Licenses
    GitHub Licensed is an open-source tool that aims to simplify the chore of ensuring license soundness and documentation for all dependencies of a GitHub project. By Sergio De Simone
  • Sauce Labs Adds Analytics and Extended Debugging to Continuous Testing Cloud
    At their recent user conference SauceCon, Sauce Labs introduced new capabilities for its continuous testing cloud including test analytics, featuring a dashboard that analyses test results and exposes common failures by browser and operating system, including Android and iOS. By Helen Beal
  • JavaFX and the Future of Java Client Technologies
    Oracle will remove JavaFX, Applets and Java Web Start from the JDK after Java SE 8. Swing and AWT will remain. By Tim Hodkinson

This is continuation with previous post on “Security in WCF -I”.

Here I’ll explain how we can implement windows authentication with transport level security in intranet environment.

Windows authentication

In intranet environment, client and service are .Net application.Windows authentication is most suitable authentication type in intranet where client credentials stored in windows accounts & groups. Intranet environment address a wide range of business applications. Developers have more controlled in this environment.

For Intranet, you can use netTcpBinding,NetNamedPipeBinding and NetMsmqBinding for secure and fast communication.

Windows credential is default credential type and transport security is default security mode for these bindings.

Protection Level

You can set Transport Security protection level through WCF:

  • None: WCF doesn’t protect message transfer from client to service.
  • Signed: WCF ensures that message have come only from authenticated caller. WCF checks validity of message by checking Checksum at service side. It provides authenticity of message.
  • Encrypted & Signed: Message is signed as well as encrypted. It provides integrity, privacy and authenticity of message.

Configuration in WCF Service for Windows Authentication

    Service is hosted on netTcpBinding with credential type windows and protection level as EncryptedAndSigned.
var tcpbinding = new NetTcpBinding(SecurityMode.Transport);
//Client credential will be used of windows user
tcpbinding.Security.Transport.ClientCredentialType = 
// When configured for EncryptAndSign protection level, WCF both signs the message and encrypts
//its content. The Encrypted and Signed protection level provides integrity,
//privacy, and authenticity.
tcpbinding.Security.Transport.ProtectionLevel = 

Client credential type can be set by TcpClientCredentialType enum.

public enum TcpClientCredentialType

Protection level can be set by ProtectionLevel  enum.

  // Summary:
    //     Indicates the security services requested for an authenticated stream.
    public enum ProtectionLevel
        // Summary:
        //     Authentication only.
        None = 0,
        // Summary:
        //     Sign data to help ensure the integrity of transmitted data.
        Sign = 1,
        // Summary:
        //     Encrypt and sign data to help ensure the confidentiality and integrity of
        //     transmitted data.
        EncryptAndSign = 2,

WCF Service Code

Service Host

class Program
static void Main(string[] args)
Uri baseAddress = new Uri("http://localhost:8045/MarketService");
using (var productHost = new ServiceHost(typeof(MarketDataProvider)))
 var tcpbinding = new NetTcpBinding(SecurityMode.Transport);
 //Client credential will be used of windows user
 tcpbinding.Security.Transport.ClientCredentialType = 
 // When configured for EncryptAndSign protection level, WCF both signs the message and encrypts
 //its content. The Encrypted and Signed protection level provides integrity,
 //privacy, and authenticity.
 tcpbinding.Security.Transport.ProtectionLevel = 

 ServiceEndpoint productEndpoint = productHost.
 AddServiceEndpoint(typeof(IMarketDataProvider), tcpbinding, 

 ServiceEndpoint producthttpEndpoint = productHost.AddServiceEndpoint(
		typeof(IMarketDataProvider), new BasicHttpBinding(), 

 Console.WriteLine("The Market service is running and is listening on:");
 Console.WriteLine("{0} ({1})",
 Console.WriteLine("{0} ({1})",
 Console.WriteLine("\nPress any key to stop the service.");


Alternatively, you can configure the binding using a config file:



    <binding name = "TCPWindowsSecurity">

     <security mode = "Transport">


                 clientCredentialType = "Windows"

                 protectionLevel = "EncryptAndSign"






Run WCF Service


Client Application

 static void Main(string[] args)
     Console.WriteLine("Connecting to Service..");
     var proxy = new ServiceClient(new NetTcpBinding(), 
	new EndpointAddress("net.tcp://localhost:8000/MarketService"));
     Console.WriteLine("MSFT Price:{0}", proxy.GetMarketPrice("MSFT.NSE"));
     Console.WriteLine("Getting price for Google");
     double price = proxy.GetMarketPrice("GOOG.NASDAQ");
  catch (FaultException ex)
       Console.WriteLine("Service Error:" + ex.Detail.ValidationError);
  catch (Exception ex)
        Console.WriteLine("Service Error:" + ex.Message);

ServiceClient is custom class which inherits ClientBase<T> class in System.ServiceModel namespace to create channels and communication with service on endpoints.

public class ServiceClient : ClientBase, IMarketDataProvider
     public ServiceClient()   { }
     public ServiceClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }
     public ServiceClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress)   { }
     public ServiceClient(string endpointConfigurationName, 
		System.ServiceModel.EndpointAddress remoteAddress) :
	        base(endpointConfigurationName, remoteAddress)
        { }
     public ServiceClient(System.ServiceModel.Channels.Binding binding, 
			System.ServiceModel.EndpointAddress remoteAddress) :
           base(binding, remoteAddress)
        /// IMarketDataProvider method
	public double GetMarketPrice(string symbol)
            return base.Channel.GetMarketPrice(symbol);

Verify User credentials in Service

You can see caller information in WCF service by ServiceSecurityContext class.  Every operation on a secured WCF service has a security call context. The security call context is represented by the class ServiceSecurityContext.The main use for the security call context is for custom security mechanisms, as well as analysis and auditing.

ServiceSecurityContext.Current in Quickwatch window.



Send Alternate Windows credentials to Service

WCF also give option to send alternate windows credential from client. By default it send logged in user credential. You can send alternate credential like below

proxy.ClientCredentials.Windows.ClientCredential.Domain = "mydomain";
proxy.ClientCredentials.Windows.ClientCredential.UserName = "ABC";
proxy.ClientCredentials.Windows.ClientCredential.Password = "pwd";

Now If I run client application with changed credentials, if credentials are of valid windows user, service will authenticate caller else it will reject caller request. In my case I deliberately gives wrong credential to produce reject exception.

Service sends “System.Security.Authentication.InvalidCredentialException with message "The server has rejected the client credentials.”


I hope you understood windows authentication concept here. If you have any question please feel free to send me comments.

You can download code here:


  1. […] Implement windows authentication and security in WCF Service […]


  2. WDV says:

    Nice one…quick and clear!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blogs I Follow

%d bloggers like this: