papadi Development Blog

.NET and Software Development by Dimitris Papadimitriou 
Filed under

WCF

 

Windows Authentication in WCF Services

Click here to download:
WindowsAuthenticationTest.zip (17 KB)

There aren't may things one has to do to enable windows authentication in a WCF service. Actually Windows Authentication is by default enabled when using most of the standard bindings of WCF.

Configuration
The following configuration ensures this anyway (use this configuration both on server and on client side):

  <system.serviceModel>
      <bindings>
          <wsHttpBinding>
              <binding name="test">
                  <security mode="Message">
                      <message clientCredentialType="Windows"/>
                  </security>
              </binding>
          </wsHttpBinding>
      </bindings>
      ...

Server
To get the credentials of the user on server side using the following (password in never included):
var identity = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity;

Client
On client you have two options:
a) Do not ask credentials from the user (Integrated Authentication): The credentials of the current logged on user will be used. This requires that the user is logged on to a Windows Domain that is trusted or is the same with the Domain of the server. There is no special code to write here. Simple instantiate the client proxy and use it.
b) Ask for Windows Credentials from the user: This is useful when you expect that your application will be used by users using machines not registered to known Windows Domains. In this case you have to create a typical log in dialog and ask for user name and password. Username must contain the domain name (Eg. MYDOMAIN\myUserName). Also this requires that the username and password the user will use belong to a domain that is trusted or is the same with the Domain of the server. In this case you also need to write the following line after instantiating your client proxy, and use the credentials you collected from the log in dialog:
clientProxy.ClientCredentials.Windows.ClientCredential = new NetworkCredential("MYDOMAIN\\myUsername", "myPassword");

Important
Patterns and Practices team created an excellent pdf document called 'WCF Security Guidance'. This is a quite big document that describes perhaps all the security scenarios that you might consider. It is organized in such a way that you can find what you are looking for quickly. Check it out!

Filed under  //   .NET   Security   WCF  

Comments [0]

WCF FAQ

Fellow MVP Shivprasad Koirala put together an excellent series of three articles with Frequently Asked Questions regarding the Windows Communication Foundation. Take a look...

WCF FAQ Part 1 : This is a 20 question FAQ for beginners which explains basic concepts of WCF like End points, contracts and bindings. It also discusses about various hosting methodologies of WCF service. The article finally ends talking about bindings and one ways operations in WCF.

WCF FAQ Part 2 : This FAQ covers 10 questions which talks about concepts like duplex contracts, hosting WCF on different protocols, MSMQ bindings, transaction isolation levels and two way communication. The article finally ends talking about two queues volatile and dead letter queue.

WCF FAQ Part 3 : 10 security related FAQ

Filed under  //   .NET   WCF  

Comments [0]

Diagram of message lifecycle in WCF service host

A collegue of mine discovered an excellent diagram on MSDN which describes the lifecycle of a WCF message when it reaches the host. The page describes how to extend dispatchers, which is kind of advanced scenario, but the diagram is very usefull to understand how the layers of WCF interact with each other and participate in the handling of a request. Check it out!

Filed under  //   .NET   WCF  

Comments [0]

My first article on CodeProject.com

I'm happy to present my first article on CodeProject.com! It's the last article of my blog, regarding Progress Indication when transferring files with 'Windows Communication Foundation'. I never new that there is such immediate response by readers in CodeProject. I already got some very useful comments on my code!

The article in CodeProject.com...
The article in this blog...

Filed under  //   .NET   WCF  

Comments [0]

File transfer with progress indication using Windows Communication Foundation

UPDATE: For latest version of this article please refer to the related article on CodeProject. Please provide comments and questions there.

This article examines the implementation of upload and download functionality with progress indication (progress bar feature) using the Windows Communication Foundation. Here is a list of what you need:

Sample code consists of three C# projects bundled in a solution. A brief description of these projects follows.

FileService

This is the main server project.

The Server Contract

File Server project includes FileTransferServiceContract.cs file which contains the IFileTransferService. This interface describes the operations provided by our server. No actual work is done in this code file except from describing the operations provided. If you worked with service oriented applications before, you know that this job is important enough to spare a separate file for. Here are the two operations of our file transfer service:

  • DownloadFile server method. Accepts a DownloadRequest instance which contains the name of the file to be downloaded by the client and returns a RemoteFileInfo instance, defined in the same code file. RemoteFileInfo contains the name of the file to be downloaded, the file stream and the length of the file in bytes. This instance of the RemoteFileInfo class will be used by the client to download the file. You notice that file name and length are marked with the MessageHeader attribute in RemoteFileInfo class. This is because when a message contract contains a stream, this can be the only body member of the contract.
  • UploadFile server method. Accepts an instance of the RemoteFileInfo message contract. This is the same used in DownloadFile, only in this case length property is not required.
[ServiceContract()]
public interface IFileTransferService
{
[OperationContract()]
void UploadFile(RemoteFileInfo request);

[OperationContract]
RemoteFileInfo DownloadFile(DownloadRequest request);
}

public class RemoteFileInfo
{
[MessageHeader(MustUnderstand = true)]
public string FileName;

[MessageHeader(MustUnderstand = true)]
public long Length;

[MessageBodyMember(Order = 1)]
public System.IO.Stream FileByteStream;
}

The Server Implementation

File Server also includes the FileTransferService.cs code file which contains the implementation of the contract, i.e. the actual code that does all the work. Apparently the included class implements the IFileTransferService class which constitutes the service contract. If you have worked with streams before in .NET you will find out that the code the handles the stream and related information for upload or download is pretty straightforward. If you are new to .NET streams, please use google for a quick introduction.

Note here that since actual downloading of the file starts after the execution of DownloadFile method is completed (i.e. after the client gets the RemoteFileInfo instance returned by this method), the server must close the opened stream later, after the client completes the process. To do this, the WaitToClose method starts in a separate thread and queries the current position of the stream once in a while. If it detects that the position of the stream remains the same for some time (1 second in our sample code) this means that the client finished downloading, failed to do so or intentionally interrupted the procedure. In any case the stream should be closed. If not, the stream will remain locked and the corresponding file will be locked for writing. (Updated on 2007/09/09) A  more elegant approache was suggested by Buddhike) To do this IDisposable interface is implemented by the RemoteFileInfo contract and the stream is disposed on the corresponding Dispose method. If this is not done the stream will remain locked and the corresponding file will be locked for writing.

ConsoleHost

FileService is a class library, hence it cannot start as a window process; therefore it needs another executable file-process that will host it. Several type processes can host a WCF service, such as .NET executables, IIS process, Windows Activation Service (new feature of Vista) and many more. Our example uses a .NET executable to host our service. So ConsoleHost is a console application that does exactly this. Is has a reference to the FileService project, however it is not related in any way with the business our service is doing, i.e. transferring files. Actually the code you will find in Program.cs would be the same even if our service was designed to host an on-line grocery. Take a quick look at this code file to understand how our service is started and closed.

static void Main(string[] args)
{
ServiceHost myServiceHost =
new
ServiceHost(typeof(FileService.FileTransferService));
myServiceHost.Open();

Console.WriteLine("This is the SERVER console");
Console.WriteLine("Service Started!");
foreach (Uri address in myServiceHost.BaseAddresses)
Console.WriteLine("Listening on " + address.ToString());
Console.WriteLine("Click any key to close...");
Console.ReadKey();

myServiceHost.Close();
}

Configuration of ConsoleHost is what matters most! It is divided into three sections and configures the way our service will behave and how it will be exposed to the rest of the world. It is not the goal of this article to describe in detail how a WCF service is configured, so please refer to the WCF reference on MSDN for more information. Something noticeable in configuration of our service is that is uses MTOM as message encoding and stream as transfer mode. See also the maxReceivedMessageSize property. This defines the maximum size of messages transferred by our service. Since we are transferring files we want this property to have a large value.

<binding name="FileTransferServicesBinding" 
transferMode
="Streamed"
messageEncoding
="Mtom"
maxReceivedMessageSize="10067108864">
binding>

Client

Client project is a sample consumer of our service. You will notice that Client project includes a folder called 'Service References'. This folder contains a bunch of files created automatically by Visual Studio, by right clicking on the Client project root and selecting 'Add Service Reference'. If you don't see this option apparently you haven't installed VS 2005 extensions for .NET 3.0. Please see the requirements at the top of this document. The files in this folder are the proxy of our file transfer service on client side. Client is using these files to send requests to the server, hiding this way the complexity of Web Service and SOAP protocols.

Again, if you have worked with streams before you will notice that things are pretty simple in the TestForm file, except one small part, which is also the difference in implementing the progress indication when uploading than when downloading. When downloading, client has the control of the procedure. You can see in the TestForm.cs that downloading is implemented using a loop that reads the server stream piece by piece. So the client knows what part of the server stream is read and how many more remains. When uploading, that loop resides on server. In order for the client to know how many bytes the server read, it uses the StreamWithProgress class which inherits the System.IO.Stream. An instance of this class is passed to the server, instead of the original file stream. And since this class overrides the default Read method of the stream (see code bellow), it can report to the client the progress of the uploading process!

public override int Read(byte[] buffer, int offset, int count)
{
int result = file.Read(buffer, offset, count);
bytesRead += result;
if (ProgressChanged != null)
ProgressChanged(this, new ProgressChangedEventArgs(bytesRead, length));
return result;
}

UPDATE: For latest version of this article please refer to the related article on CodeProject. Please provide comments and questions there.

Filed under  //   .NET   C#   WCF  

Comments [0]

Getting started with Windows Communication Foundation

Yesterday, I presented WCF in the 8th dotNETZone.gr event, in Microsoft Hellas building in Athens. Here is a list of resources that may help you get started with Windows Communication Foundation.

Software:

If you like reading first, you can find lot's of information by clicking the following links:

If you are the type of guy that prefers to dig into the code directly, in MSDN you will find a package of more than 140 samples!

Filed under  //   .NET   WCF   WPF  

Comments [0]

Windows Communication Foundation - The basics

Windows Communication Foundation (WCF - formerly known as Indigo) encapsulates all previous microsoft technologies for remoting and messaging. It's layered architecture consists of a base that handles asynchronous calls and message handling and a top that handles security, transations, transport and encoding capabilities.

WCF acts as a wrapper of preceding remoting technologies like:

  • ASP.NET Web Services: The Microsoft's implementation for XML web services
  • .NET Remoting: Supports .NET to .NET tight coupled communication in favor of performance.
  • Enterprise Services: One of the oldest remoting technologies, also known as COM+ prior to introducing .NET. Part of it was DCOM and event older remoting method. Supports distributed transactions (eg. transactions among multiple databases and physical computers).
  • WSE: Web Services Enhancements. WCF supports only version 3 of WSE, a set of enhancements for handling stuff like security and routing.
  • MSMQ: Microsoft Message Queue provides guaranteed message delivery and is optimized for unreliable communications or systems that require off-line support.

Being a wrapper of all that techonologies, WCF encapsulates all possible features of them:

  • SOAP (Simple object access protocol is used to create "envelopes" for carrrying messages)
  • Plain XML and RSS (although SOAP is the main protocol for message delivery for WCF, plain XML or RSS are fully supported)
  • Binary XML, MTOM (binary representation of XML files used to transfer large files. Trades message readability and interoperability for performance)
  • WSE Features and may others...

WCF services - applications that expose services using WCF - must be hosted by a process and be ready to accept and respond to requests. These processing could be hosted by:

  • IIS : Internet Information Services provides scalability, manageability and security)
  • Windows Activation Service : Introduced with Windows Vista, is the new process activation mechanism that ships with IIS 7.0.
  • Exe : Any custom .NET executable (eg. Windows Forms or Console application) can host WCF services
  • Windows Service
  • COM+ Component

Filed under  //   .NET   IIS   WCF  

Comments [0]