Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C#

Implement Windows Authentication and Security in WCF Service

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
13 Jan 2012CPOL2 min read 84.5K   24   7
This is a continuation of the previous post on “Security in WCF - I”.

This is a continuation of the 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 applications. Windows authentication is the most suitable authentication type in intranet where client credentials are stored in Windows accounts & groups. Intranet environment addresses a wide range of business applications. Developers have more control 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 has 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.
C#
var tcpbinding = new NetTcpBinding(SecurityMode.Transport);
//Client credential will be used of windows user
tcpbinding.Security.Transport.ClientCredentialType =
        TcpClientCredentialType.Windows;
// 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 =
System.Net.Security.ProtectionLevel.EncryptAndSign;

Client credential type can be set by TcpClientCredentialType enum.

C#
public enum TcpClientCredentialType
{
    None,
    Windows,
    Certificate
}

Protection level can be set by ProtectionLevel enum.

C#
// 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

C#
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 =
            TcpClientCredentialType.Windows;
            // 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 =
            System.Net.Security.ProtectionLevel.EncryptAndSign;

            ServiceEndpoint productEndpoint = productHost.
            AddServiceEndpoint(typeof(IMarketDataProvider), tcpbinding,
            "net.tcp://localhost:8000/MarketService");

            ServiceEndpoint producthttpEndpoint = productHost.AddServiceEndpoint(
            typeof(IMarketDataProvider), new BasicHttpBinding(),
            "http://localhost:8045/MarketService");

            productHost.Open();
            Console.WriteLine("The Market service is running and is listening on:");
            Console.WriteLine("{0} ({1})",
             productEndpoint.Address.ToString(),
             productEndpoint.Binding.Name);
            Console.WriteLine("{0} ({1})",
             producthttpEndpoint.Address.ToString(),
             producthttpEndpoint.Binding.Name);
            Console.WriteLine("\nPress any key to stop the service.");
            Console.ReadKey();
        }
    }
}

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

XML
<bindings>
<netTcpBinding>
    <binding name = "TCPWindowsSecurity">
     <security mode = "Transport">
          <transport
                 clientCredentialType = "Windows"
                 protectionLevel = "EncryptAndSign"
           />
     </security>
</binding>
</netTcpBinding>
</bindings>

Run WCF Service

image

Client Application

C#
static void Main(string[] args)
{
    try
    {
        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);
    }
    Console.ReadLine();
}

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

C#
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)
        {}
        ///<summary>
        /// IMarketDataProvider method
        /// </summary>
        ///
        ///
    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.

image

Send Alternate Windows Credentials to Service

WCF also gives an option to send alternate Windows credential from the client. By default, it sends logged in user credential. You can send alternate credentials like below:

C#
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 give wrong credential to produce reject exception.

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

image

I hope you understood the Windows authentication concept here. If you have any questions, please feel free to send me comments.

You can download the code from here.

Image 4 Image 5 Image 6 Image 7 Image 8 Image 9 Image 10 Image 11

License

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


Written By
Architect Saxo Bank A/S
Denmark Denmark
• Solution Architect /Principle Lead Developer with 12 years of IT experience with more emphasize on Capital Domain and Investment banking domain.
• Strong experience in Continuous Integration, Delivery and DevOps solutions.
• Strong experience in drafting solutions, stakeholder communications and risk management.
• Proved strong coding and designing skills with agile approaches (TDD, XP framework, Pair Programming).
• Delivered many projects with involvement from inception to delivery phase.
• Strong experience in high performance, multithreaded, low latency applications.
• Ability to communicate with the business and technical stake holders effectively.
• Have extensive experience in Capital Market Domain: Front Office & BackOffice (Algorithm Trading tools, messaging framework, Enterprise bus, integration of FIX APIs and many trading APIs).
• Functional knowledge of Portfolio/Wealth Management, Equities, Fixed Income, Derivatives, Forex.
• Practical knowledge of building and practicing agile delivery methodologies (SCRUM, TDD, Kanban).

Technical Skills

• Architectural: Solution Design, Architectural Presentations (Logical, Component, Physical, UML diagrams)
• Languages: C#, C++
• Server Technologies: WCF, Web API,
• Middle Ware: ActiveMQ, RabbitMQ, Enterprise Service Bus
• UI Technologies: Winforms and WPF
• Web Technologies: Asp.Net Mvc, KnockOutJS, JQuery, Advance Java Scripts Concepts
• Databases: Sql Server 2008 +, MySQL
• Tools/Frameworks: TFS, SVN, NUnit, Rhino Mocks, Unity, NAnt, QuickFix/n, Nhibernate, LINQ, JIRA,

Functional Skills

• Wealth Management System, Trade Life Cycle, Trading Components and their integrations
• Working knowledge of Stocks, Bonds, CFDs,Forex, Futures and Options
• Pricing Systems, Market Data Management,
• BackOffice Processes : Settlement Processes, Netting, Tax, Commissions, Corporate Actions Handling,
• Reporting Solutions : OLTP and OLAP Data model designing
• FIX Engine implementation and integration

Comments and Discussions

 
QuestionI meant changing Client Credentials does not really change any credential Pin
Member 701715428-Jul-17 8:50
Member 701715428-Jul-17 8:50 
QuestionNice article but the part of the unauthorized Client does not work Pin
Member 701715428-Jul-17 8:38
Member 701715428-Jul-17 8:38 
QuestionNice article but the part of the unauthorized Client does not work Pin
Member 701715428-Jul-17 8:36
Member 701715428-Jul-17 8:36 
QuestionNeat article - but the source code link is broken Pin
Sau0028-Apr-13 7:19
Sau0028-Apr-13 7:19 
Questionvery nice article Pin
nasser200927-Nov-12 5:32
nasser200927-Nov-12 5:32 
AnswerRe: very nice article Pin
Neeraj Kaushik19801-Dec-12 7:19
Neeraj Kaushik19801-Dec-12 7:19 
Generalthe source code link is broken Pin
kamskyleo211-Jun-12 19:21
kamskyleo211-Jun-12 19:21 

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.