WCF

What is a fault contract?
Normally, by default, when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client using Fault Contract.“So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.”WCF Fault
 [ServiceContract]
 public interface IService1
 {
        [OperationContract]
        [FaultContract(typeof(MyFaultDetails))]
        int MyOperation1();
 }
 [DataContract]
  public class MyFaultDetails
  {
        [DataMember]
        public string ErrorDetails { get; set; }
  }
In implementing service…..
  public int MyOperation1()
  {
       Try{               //Do something……       }catch()
       {
                  MyFaultDetails ex = new MyFaultDetails();
                  ex.ErrorDetails = “Specific error details here.“;
                  throw new FaultException(ex,“Reason: Testing…..“);
       }
  }
For understanding detailed difference between .NET Exception and WCF Fault,
A user has a service with a one-way operation that includes a fault contract, and he gets an exception when he tries to host the service. Why?
This is true, because, to return faults, the service requires some form of a two-way communication channel, which is not there with one-way operations.

What are the core security concepts supported by WCF?
There are four core security FeaturesWCF Security Concepts
Confidentiality: It’s a confirmation about the recipient. Only the valid recipient can read the message when it passed between service and client.
Integrity: is to ensure that message received is not being tempered or changed during exchange.
Authentication: is a way for the parties (sender and receiver) to identify each other.
Authorization: ensures that what actions an authenticated user can perform?

Difference between Message Level security and Transport Level security?
Security can be configured at two different levels in Windows Communication Foundation:
Transport Level Security
secures the transport (the pipe) over which the message passes through from client to a service.
Message Level Security
secures the message that is being transported from one end to another.
WCF Supports following Transfer Security Modes:
None – No security at all. Very risky to choose.
Transport – Securing message transfer with transport protocol like TCP, IPs, HTTPs, MSMQ.  It’s Ideal for Intranet scenarios having point to point communication.
Message – Securing message by encrypting it. Good for scenarios even when multiple intermediaries involved.
Mixed – TransportWithMessageCredential uses transport for message privacy and service authentication with client authentication handled at message level.
Both -Using both Message as well as transport security. In this case a secured encrypted message travel over a secure transport (pipe) only supported by MSMQ Binding.

<wsHttpBinding>
       <binding name=”SecurityModeDemo”>
                    <security mode=”[None|Transport|Message|….]”/>
       </binding>
</wsHttpBinding>

Can you please explain which security mode supported by various WCF Bindings?
Following table illustrates in details about support for security mode in Windows Communication Foundation for various WCF Bindings.
WCF Binding
None
Transport
Message
Mixed
Both
                                 None   Tran. Mesg Mixed Both
BasicHttpBinding  Default Yes Yes    Yes No
WSHttpBinding  Yes   Yes Default Yes No
WSDualHttpBindingYes        No Default Yes No
NetTcpBinding  Yes   Default   Yes Yes No
NetNamedPipeBinding Yes Default No No No
NetMsmqBinding  Yes Default Yes No Yes


Difference between BasicHttpBinding and WsHttpBinding w.r.t Security?

WsHttpBinding supports advanced WS-* specification, it has a lot more security options available. For example, It provides message-level security i.e. message is not sent in plain text. Also it supports for WS-Trust and WS-Secure conversation.
While in case of BasicHttpBinding, it has fewer security options, or we can say, there is no security provided, by default. At transport level, it can provide confidentiality through SSL.

Please explain about authorization options supported in WCF?
Authorization as a core feature of security in WCF supports different authorization types.

Role-based authorization is the most common authorization approach being used. In this approach, authenticated user has assigned roles and system checks and verifies that either a specific assigned role can perform the operation requested.
Identity-based authorization approach basically provides support for identity model feature which is considered to be an extension to role-based authorization option. In this approach, service verifies client claims against authorization policies and accordingly grant or deny access to operation or resource.
For more details on Authorization with Identity Model, please follow here.
Resource-based authorization approach is a bit different because it’s applied on individual resources and secure those using windows access control lists (ACLs).


What is Reliable Messaging in WCF?
We know that networks are not perfect enough and those might drop signals or in some scenarios there can be a possibility of wrong order of messages during message exchange.
WCF allows us to ensure the reliability of messaging by implementing WS-ReliableMessaging protocol.  Here is how you can configure reliable messaging in WCF.

 <wsHttpBinding>
    <binding name=”Binding1″>
                  <reliableSession
                                         enabled=”true”
                                        ordered=”true”
                                        inactivityTimeout=”00:02:00″ />
     </binding>
  </wsHttpBinding>

What are Reliable Sessions in WCF?
Reliable sessions actually ensure that the caller for messages will know about the lost message(s) but it can’t guarantee about the delivery of message(s).
There is a misconception about reliable sessions that it ensures the session will never expire or stays for a very long time. This we can achieve by using timeout for sessions.

What are the different ways to expose WCF Metadata?
By default, WCF doesn’t expose metadata. We can expose it by choosing one of the following ways:
1.    In configuration file, by enabling metadata exchange as follows:Expose WCF Service Metadata
2.  ServiceHost can expose a metadata exchange endpoint to access metadata at runtime.
   using (ServiceHost host = new ServiceHost(typeof(WcfService1)))
   {
              ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
              behavior.HttpGetEnabled = true;
              host.Description.Behaviors.Add(behavior);
              host.Open();
              Console.WriteLine(“My Service here……….”);              Console.ReadLine();
              host.Close();
   }

What is mexHttpBinding in WCF?
In order to generate proxy, we need service metadata and mexHttpBinding is the binding that returns service metadata.
If we look into our configuration file, service will have an endpoint with mexHttpBinding as follows:mexHttpBinding
and service metadata behavior will be configured as follows:httpGetEnabled
Before deployment of application to production machine, it should be disabled.
In order to support other protocols, related bindings are:

  1. mexHttpBinding
  2. mexHttpsBinding
  3. mexTcpBinding


What is a Service Proxy in Windows Communication Foundation?
A service proxy or simply proxy in WCF enables application(s) to interact with WCF Service by sending and receiving messages. It’s basically a class that encapsulates service details i.e. service path, service implementation technology, platform and communication protocol etc. It contains all the methods of service contract (signature only, not the implementation). So, when the application interact the service through proxy, it gives the impression that it’s communicating a local object.
WCF Service ProxyWe can create proxy for a service by using Visual Studio or SvcUtil.exe.


What are the different ways to generate proxy in WCF?
Generating proxy using Visual Studio is simple and straight forward.
Right click References and choose “Add Service Reference”.
Provide base address of the service on “Add Service Reference” dialog box and click “Go” button. Service will be listed below.
Provide namespace and click OK.
Visual studio will generate a proxy automatically.

We can generate proxy using svcutil.exe utility using command line. This utility requires few parameters like HTTP-GET address or the metadata exchange endpoint address and a proxy filename i.e. optional.
svcutil http://localhost/MyService/Service1.svc /out:MyServiceProxy.cs

If we are hosting the service at a different port(other than default for IIS which is 80), we need to provide port number in base address.
svcutil http://localhost:8080/MyService/Service1.svc /out:MyServiceProxy.cs

For parameter details regarding svcutil, please follow the MSDN link
http://msdn.microsoft.com/en-us/library/aa347733.aspx

Difference between using ChannelFactory and Proxies in WCF?
A ChannelFactory creates a kind of Channel used by clients to communicate with service endpoints. If we have control over Server and Client, then ChannelFactory is a good option because it relies on having local interfaces that actually describes the service i.e. service contract.

On the other hand, If we don’t have control over server and only have WSDL/URL, then it’s better to generate proxy using Visual Studio or SvcUtil. SvcUtil is better option as compared to Visual Studio because we have more control in case of SvcUtil.

How to create proxy for Non-WCF Services?
In case of Non-WCF Services, we can create proxy by either using Visual Studio or svcUtil.exe tool by pointing to WSDL of the non-WCF service. In this scenario, we can’t create proxy through ChannelFactory or manually developing proxy class because we don’t have local interfaces i.e. service contract.

Breifly explain Automatic Activation in WCF?
Automatic activation means service starts and serves the request when a message request is received, but service doesn’t need to be running in advance.
Both IIS (Internet Information Services) and WAS (Windows Activation Service) supports automatic activation. It means if your service is hosted in IIS or WAS, then it will be activated automatically as a new message
arrives. But there are few scenarios in which service needs to be running in advance, for example, in case of Self-

Hosting.Automatic Activation in WCF

Note: WAS (Windows Activation Service) is a process activation mechanism introduced in IIS 7.0 that supports other protocols (e.g. TCP, NamedPipes etc.) along with existing HTTP.
If you want to go into details and see the implementation of different available hosting options in WCF, you can follow the below WCF Service Hosting Tutorials.

  1. WCF Console Hosting
  2. Hosting in Windows Service
  3. Hosting in IIS (Internet Information Service)
  4. WCF WAS (Windows Activation Service) Hosting

What are the different WCF Instance Activation Methods available?
WCF supports three different types of Instance Activation methods:
Per Call: A new instance is created against each incoming request from client and later disposed off  as response generated.WCF PerCall
Per Session: an instance for each session.WCF Per Session
Singleton: All incoming requests are served by only one instance.WCF Singleton mode
For details on WCF Instance Management, please refer other article “3 techniques for Instance Management in WCF”.


What are the different ways to handle concurrency in WCF?
There are three different ways to handle concurrency in WCF that are:

  1. Single
  2. Multiple
  3. Reentrant

Single: means at a given time, only a single request can be processed by WCF service instance. Other requests will be waiting until the first one is fully served.
Multiple: means multiple requests can be served by multiple threads of a single WCF service instance.
Reentrant: means a single WCF service instance can process one request at a given time but the thread can exit the service to call another service.
We can apply these concurrency settings by putting ConcurrencyMode property in ServiceBehavior as follows:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple] public class MyService : IMyService
{
}

What is WCF throttling?
WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent sessions. Basic purpose is to control our WCF service performance by using Service throttling behavior.
In configuration file we can set this behavior as follows:
 
 <serviceBehavior>
        <behavior name=”MyServiceBehavior”>
                    <serviceThrottling
                                     maxConcurrentInstances=”2147483647”
                                     maxConcurrentCalls=”16″
                                     maxConcurrentSessions=”10″
         </behavior>
   </serviceBehavior>

Above given values are the default ones, but we can update it after looking into the requirements of our application.

3 Ways to generate proxy for WCF Service

  1. In Windows Communication Foundation, for a client application to communicate with a WCF Service, we have following options:
  2. Using ChannelFactory
  3. Generating Proxies
  4. “A Proxy in Windows Communication Foundation is a class that enables client applications to communicate with a service by sending and receiving messages. It actually encapsulates a number of service details like service path, service implementation technology, platform being used, communication protocol etc. as well as all the methods (signature only) of the Service Contract.”WCF Service Proxy

Windows Communication Foundation supports following three ways to generate proxy for a WCF Service.
1. Adding Service Reference
2. Implementing ClientBase
3. Using Tool i.e. SvcUtil.exe

So, in this WCF Tutorial, we will carry out all three possible ways to generate proxy for a WCF service. Let’s create a simple WCF Service first.
Create WCF Service
Option 1: Generate Proxy Adding Service Reference
Implementation of generating proxy by adding a service reference is also available here for the same WCF service i.e. “StudentService”.
Option 2: Generate Proxy by implementing ClientBase<T> class
Generating proxy by using ClientBase<T> class option has an advantage that it creates proxy at run time, so it will accommodate service implementation changes. Let’s follow the steps to generate proxy.
Add a Client Project to solution named as “ClientApp2” that is basically a Console Application.
ClientBase Proxy
Add reference of StudentService Project to ClientApp2.
Add following proxy class using ClientBase<T> as:
  public class StudentServiceProxy : ClientBase<IStudentService>, IStudentService
  {
           public string GetStudentInfo(int studentId)
           {
                 return base.Channel.GetStudentInfo(studentId);
           }
  }
Note: Don’t forget to add “using StudentService” to class.
Following is the code for program.cs class in ClientApp2. We are using above created proxy class to communicate with WCF Service “StudentService“.
 class Program
 {
         static void Main(string[] args)
         {
                     StudentServiceProxy myclient;
                     myclient = new StudentServiceProxy();

                     int studentId = 1;
                     Console.WriteLine(“Calling StudentService with StudentId = 1…..”);
                     Console.WriteLine(“Student Name = {0}”, myclient.GetStudentInfo(studentId));
                     Console.ReadLine();
         }
  }
Note: Don’t forget to add “using System.ServiceModel” to class.
App.Config file will have following configuration:
  <system.serviceModel>
            <bindings>
                <wsHttpBinding>
                    <binding name=”WSHttpBinding_IStudentService” />
                </wsHttpBinding>
            </bindings>
            <client>
                 <endpoint address=”http://localhost:4321/StudentService”
                                  binding=”wsHttpBinding”
                                  bindingConfiguration=”WSHttpBinding_IStudentService”
                                  contract=”StudentService.IStudentService”
                                  name=”WSHttpBinding_IStudentService”>
                 </endpoint>
             </client>
  </system.serviceModel>
Now, when we run the client application, we will receive the following same output as we get in earlier option “Adding Service Reference”.
WCF Proxy
Option 3: Generate Proxy by using SvcUtil.exe Tool
Let’s generate proxy by using third option i.e. SvcUtil.exe Tool by following step by step approach.
Add a Client Project to solution named as “ClientApp3” that is basically a Console Application.
SvcUtil Tool
Our WCF Service must be running, so let’s run our service.
WCF Service Running
Open Visual Studio Command Prompt and generate proxy using svcutil.exe tool as follows:
svcutil http://localhost:4321/StudentService /out:StudentServiceProxy.cs

SvcUtil Command
It will generate a new class “StudentServiceProxy.cs”.

Add newly created proxy class to our client application “ClientApp3”.
Call WCF Service using proxy class as:
  class Program
  {
          static void Main(string[] args)
          {
                     StudentServiceClient myclient;
                     myclient = new StudentServiceClient();
                     int studentId = 1;
                     Console.WriteLine(“Calling StudentService with StudentId = 1…..”);
                     Console.WriteLine(“Student Name = {0}”, myclient.GetStudentInfo(studentId));
                     Console.ReadLine();
           }
  }
When we run the application, it will call StudentService method getStudentInfo and generate the same output as we received in other options.

=============
Difference between using ChannelFactory and Proxies in WCF?
A ChannelFactory creates a kind of Channel used by clients to communicate with service endpoints. If we have control over Server and Client, then ChannelFactory is a good option because it relies on having local interfaces that actually describes the service i.e. service contract.
On the other hand, If we don’t have control over server and only have WSDL/URL, then it’s better to generate proxy using Visual Studio or SvcUtil. SvcUtil is better option as compared to Visual Studio because we have more control in case of SvcUtil.

Questions list ::
Design Considerations
How do I decide on an authentication strategy?
How do I decide on an authorization strategy?
When should I use message security versus transport security?
How do I use my existing Active Directory infrastructure?
What bindings should I use over the Internet?
What bindings should I use over an intranet?
When should I use resource-based authorization versus roles-based authorization?
When should I impersonate the original caller?
When should I flow the original caller's identity to back-end resources?
How do I migrate to WCF from an ASMX Web service?
How do I migrate to WCF from a COM application?
How do I migrate to WCF from a DCOM application?
How do I migrate to WCF from a WSE application?

Auditing and Logging

What WCF service security events should be logged?
How do I enable logging and auditing in WCF?
How do I stop my service if there has been an auditing failure?
How do I log important business events in WCF?
How do I implement log throttling in WCF?
How do I use the health monitoring feature with WCF?
How do I protect my log files?
How do I pass user identity information in a message for auditing purpose?

Authentication
When should I use the SQL Server membership provider?
How do I authenticate against Active Directory?
How do I authenticate against a SQL store?
How do I authenticate against a custom store?
How do I protect passwords in my user store?
How do I use certificate authentication with X.509 certificates?
What is the most common authentication scenario for intranet applications?
What is the most common authentication scenario for Internet applications?
How do I support authentication for multiple client types?
What is federated security?
How do I send credentials in the message when I am using transport security?
How do I avoid cleartext passwords?
Authorization
How do I decide on an authorization strategy in WCF?
What is the difference between resource-based, roles-based, and claims-based authorization?
How do I use Windows groups for role authorization in WCF?
How do I use the SQL Server role provider for ASP.NET role authorization in WCF?
How do I use the Windows Token role provider for ASP.NET role authorization in WCF?
How do I use the Authorization Store role provider for ASP.NET role authorization in WCF?
What is the difference between declarative and imperative roles authorization?
How do I restrict access to WCF operations to specific Windows users?
How do I associate roles with a certificate?
What is a service principal name (SPN)?
How do I create a service principal name (SPN)?

Bindings
What is a binding?
What bindings are available?
Which bindings are best suited for the Internet?
Which bindings are best suited for an intranet?
How do I choose an appropriate binding?

Configuration Management

How do I encrypt sensitive data in the WCF configuration file?
How do I run a WCF service with a particular identity?
How do I create a service account for running my WCF service?
When should I use a configuration file versus the WCF object model?
What is a metadata exchange (mex) binding?
How do I keep clients from referencing my service?

Deployment Considerations
What are the additional considerations for using WCF in a Web farm?
How do I configure Active Directory groups and accounts for roles-based authorization checks?
How do I create an X.509 certificate?
When should I use a service principal name (SPN)?
How do I configure a least-privileged account for my service?

Exception Management
How do I implement a global exception handler?
What is a fault contract?
How do I define a fault contract?
How do I avoid sending exception details to the client?

Hosting
How do I configure a least-privileged account to host my service?
When should I host my service in Internet Information Services (IIS)?
When should I host my service in a Windows service?
When should I self-host my service?

Impersonation/Delegation
What are my impersonation options?
What is the difference between impersonation and delegation?
How do I impersonate the original caller for an operation call?
How do I temporarily impersonate the original caller in an operation call?
How do I impersonate a specific (fixed) identity?
What is constrained delegation?
What is protocol transition?
How do I flow the original caller from the ASP.NET client to a WCF service?
What is the difference between declarative and programmatic impersonation?
What is the trusted subsystem model?
When should I flow the original caller to back-end code?
How do I control access to a remote resource based on the original caller's identity?

Input/Data Validation
How do I implement input and data validation in WCF?
What is schema validation?
What is parameter validation?
Should I validate before or after message serialization?
How do I protect my service from denial of service (DoS) attacks?
How do I protect my service from malicious input attacks?
How do I protect my service from malformed messages?

Message Protection
When should I use message security?
When should I use transport security?
How do I protect my message when there are intermediaries routing the message?
How do I protect my message when there are multiple protocols used during message transit?

Proxy Considerations
When should I use a channel factory?
When do I need to expose a metadata exchange (mex) endpoint for my service?
How do I avoid proxy spoofing?

Sensitive Data
How do I protect sensitive data in configuration files?
How do I protect sensitive data in memory?
How do I protect my metadata?
How do I protect sensitive data from being read on the wire?
How do I protect sensitive data from being tampered with on the wire?

X.509 Certificates
How do I create X.509 certificates?
Do I need to create a certificate signed by the root CA certificate?
How do I use X.509 certificate revocation?

No comments:

Post a Comment