Silverlight Hack

Silverlight & related .NET technologies

About Me

Welcome to Silverlighthack.com.  This is a site where you can find many articles on Silverlight, Windows Phone 7 and .NET related technologies.  

My name is Bart Czernicki.  I have been working with computers since 1988 and have over 12 professional years in the IT field focusing on architecture, technology strategy and product management.  I currently work as a Sr. Software Architect at a large software development company.

Below is the cover of my new book that shows how Silverlight's unique RIA features can be applied to create next-generation business intelligence (BI 2.0) applications.

Silverlight 4 Business Intelligence Soft 

Contact: bartczernicki@gmail.com

View Bart Czernickis profile on LinkedIn

NONE of the comments or opinions expressed here should be considered ofmy past or current employer(s).  The code provided is as-is without anyguarantees or warranties.

WCF 101 - Understanding Transfer Security Visually

Overview 

WCF includes a variety of security settings and design options.  One of the security options the service architect has to worry about is transfer security.  Transfer security deals with ensuring safe and secure communication between a client and service host. 

Transfer security is very important for several reasons.  Even the best authorization and authentication service design means nothing if the messages are not secure.  Unsecure messages can lead to a variety of problems like:

  • exposing the message contents to the outside world including hackers
  • exposing other security mechanisms on how to compromise your service (authentication or authorization)
  • spoofed messages (By mimicking certain message patterns, hackers can create fake messages that can cause your service to end up corrupted.)
  • DOS attacks
WCF Transfer Security Implementation

WCF provides a variety of ways to secure the communication channel between the service and the client.  Using these options properly can lead to highly secure communication with a very low probability of your messages being compromised.  Conversely,  even missing a small setting in the transfer security configuration can lead to messages that can have compromised privacy or integrity.

Generally speaking, WCF supports four different ways to secure your service transfer mechanism:

  • Transport - This secures the messages by using a secure protocol that encrypts the entire channel that the messages are flowing over.
  • Message - This secures the messages by encrypting the messages themselves.
  • Both - This method combines both Transport and Message security.  This secures the messages by encrypting the messages themselves and encrypting the channel.
  • Mixed - This method uses Transport security to protect the message contents.   However, message security is used to protect the credentials of the user.

A developer who is not experienced with WCF might have a hard time comprehending these concepts initially.  Therefore, I decided to show at a very high level how you can understand these transfer security modes visually.

Unsecure (None) Transfer Security

Messages are unencrypted over a channel stack that is unsecure

  • Messages are are unencrypted and the channel is unencrypted as well.
  • Unsecure transfer security is obviously not recommended.
  • Services DO NOT have to have content you want to protect in order to provide message security.   Without properly protecting your messages, your service can be exposed to hackers and it could cause unwanted performance problems as well attacks like relay or DOS attacks can bring the entire service down.
Message Transfer Security

Messages are encyrpted over a channel stack that is unsecure

  • Individual messages are encrypted.
  • Message transfer adds the most overhead and latency to the WCF service (other than the Both/Mixed option)
    • Each message needs to be properly encrypted and encoded as it leaves the client or service.
    • Each message needs to verified that it was not tampered with when it is received.
Transport Transfer Security

Messages are unencyrpted over a channel stack that is secure (If the channel were unsecure, you could see the messages in clear text.)

  • The messages are not encrypted; however, the channel is secure through using a secure protocol.
  • The communication channel is set up intially and transport security can take advantage of hardware acceleration and thus, can be further optomized.
  • Transport security is point to point.  Since the messages themselves are not encrypted, once they go to another point, they can be potentially exposed to integrity/privacy attacks as if they were unsecure.
Message Transfer Security (mulitple hops)

Messages are encyrpted over an unsecure channel between the client and the service endpoint (1st hop).  Notice the messages remain encrypted between the first service and second service (2nd hop).

  • The big advantage of message security is that it provides end to end security.
    • Messages leaving intermediary services retain their security.
  • Message security is not provided by all bindings and it is considered the best practice when designing enterprise services organized in a "matrix".
Transport Transfer Security (multiple hops)

Messages are unencyrpted over an secure channel between the client and the service endpoint (1st hop).  Notice the messages DO NOT remain encrypted between the first service and second service (2nd hop).

  • The big disadvantage of transport security is that it is only guaranteed to be point to point.
  • Message leaving and the intermediate service are not secure (by default).
  • Messages can be secured in the 2nd hop; however, it requires additional work.

Silverlight supports Transport level security natively out of the box with WCF configuration.  Message security is possible inside Silverlight; however, it does require additional advanced programming beyond setting simple binding/behavior settings.  However, message security is not 100% supported with all the different options like securing Messages with credentials.

Summary

In this article, I introduced the basics of WCF transfer security design scenarios.  I decided to show the differences visually so that this concept is easier to understand for those new to WCF.

kick it on DotNetKicks.com
Posted: Dec 10 2008, 16:27 by Bart Czernicki | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .net | WCF
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Silverlight enabled WCF Service Template is Bad Practice

Silverlight-enabled WCF Service  Template

Visual Studio 2008 SP1 with the Silverlight Tools includes a new template that makes creating a WCF service that can be consumed with Silverlight very easy.  Once you you have the Silverlight Tools installed, you can use the template when adding a new item:

Adding a WCF service based on this template does several things for us:

  • Like any other WCF Service template, this adds the refrences to all the necessary System.ServiceModel assemblies.
  • It adds a WCF endpoint based on the BasicHttpBinding (which is one of the three Silverlight supports natively); Modifies the web.config with the endpoint information.
  • Adds a class/contract baseline information to our service class.
  • The service can be consumed by a Silverlight 2 client with no other necessary configuration (excluding deployment considerations).

Let's take a look at the code that was generated from the service template:

namespace SilverlightApplication1.Web{[ServiceContract(Namespace = "")][AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]public class Service1{[OperationContract]public void DoWork(){// Add your operation implementation herereturn;}// Add more operations here and mark them with [OperationContract]}}

Above what we have is a public class called Service1 with one method DoWork().  The service is decorated with an attribute called ServiceContract (ServiceContractAttribute).  This tells the client what operations can be called on the service.  Applying the ServiceContract attribute on a class (or interface) exposes the type to service consumers.  WCF works on an opt-in model and methods need to explicitly configured to be exposed in the service.  This is what the OperationContract attribute (OperationContractAttribute) is for.  You apply this attribute on any methods that you want the client to be able to call through the service.  These two attributes are all that is needed to expose a service publicly. 

The problem with the template implementation is that it places the attributes directly on the class itself.  This obviously is a bad practice as it couples the service implementation and the class implementation together.  If you have read any architecture books/resources, this paradigm is not new to you.  Why is it bad for WCF?  When designing a WCF service, a developer needs to prepare for future use of the service and be ready for possible changes.  The more places you make changes causes the more items that could potentially break.  This could cause QA to be involved in re-testing certain parts of the program.  We obviously want to split this up so that the service design/contract (what types and what methods the service exposes) are seperated from actual implementation (what the DoWork() method does).  Another reason we want to break the contract and implementation is so that the contracts can be re-used on the client.  WCF includes a lot of gotchas especially when generating a proxy on the client.  What actually happens when you generate a proxy is that these types and the service exposed methods actually are generated on the client class inside the proxy.  You can mitigate lot of these issues by simply having the service contract types on the client. (I will cover this in another article; showing how to create an assembly that can be used both in Silverlight and .NET that shares service contracts).

Interfaces - The real Service Contracts 

By defintion, an interface is a contract that a class implementing has to adhere to.  Interfaces by definition fit the WCF structure very well here and we should define our service contracts (how the service will be designed) in our interface and then have our class implement this design.  You can see we are essentially factoring out the structure of our services all in our interfaces and then creating the actual implementation in our classes (how the service is going to do these operations).  In any WCF book you will read, it is stated over and over that the service/operation attributes should be placed on the interface rather than directly on the classes.

As you can see above, the template applied these service contracts directly on the class.  This is obviously a bad practice in WCF design.  Let's re-work the template above so we can create a service design that is factored outside of the implementation.  First, we can create an interface with one method DoWork() and apply the proper attributes and it will look like this:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceModel;namespace SilverlightApplication1.Web{[ServiceContract(Namespace = "")]interface IService1{[OperationContract]void DoWork();}}

Now we can refactor our Service1 class and simply implement the interface.  Notice I removed the ServiceContract and OperationContract attributes as they are now on the interface.  (Note: The AspNetCompatibilityRequirements attribute can ONLY be applied on a class, and this attribute is really there for backwards compatibility with ASP.NET and in true WCF rarely will you see it used).

using System;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Activation;using System.Collections.Generic;using System.Text;namespace SilverlightApplication1.Web{[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]public class Service1 : IService1{public void DoWork(){// Add your operation implementation herereturn;}// Add more operations here and mark them with [OperationContract]}}

If you had followed the steps above, the service would not work when accessed.  The service will error and say that the contract could not be found.

 

When the template generated the WCF configuration, the ServiceContractAttribute was applied to on the class directly.  The service is looking for a type called Service1.  WCF and the configuration is not smart enough to know that we have an interface called IService1 and that Service1 is a class that implements that contract.  Therefore, we have to explicity give the name of the class or interface that has the ServiceContractAttribute applied to it.  In our example, this is the IService1 interface.  We simply need to change service configuration inside the web.config from this:

<service behaviorConfiguration="SilverlightApplication1.Web.Service1Behavior" name="SilverlightApplication1.Web.Service1">

  <endpoint address="" binding="basicHttpBinding" contract="SilverlightApplication1.Web.Service1"/>

  <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

to this:

<service behaviorConfiguration="SilverlightApplication1.Web.Service1Behavior" name="SilverlightApplication1.Web.Service1">

  <endpoint address="" binding="basicHttpBinding" contract="SilverlightApplication1.Web.IService1"/>

  <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

</service>

Summary

The Silverlight-enabled WCF Service Template is a nice way to get started with implementing a Silverlight-based service.  However, because the contract definitions are directly applied to the class, it should not be used as guidance on how one should lay out their WCF design.  As you saw above, it is quite easy to refactor the service design from the implementation in a couple of steps.  This allows your WCF service to follow WCF best practice guidelines.  The template is a good starting point for starting a Silverlight WCF project but only after refactoring the initial contract.  In the next article I will show how to refactor the contracts into an assembly both the service and the client (service consumer) can share.

 

kick it on DotNetKicks.com
Posted: Dec 04 2008, 15:37 by Bart Czernicki | Comments (6) RSS comment feed |
  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Silverlight | WCF
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Best WCF Book and WCF Resource - 2nd Edition

Update 12/5/2010: The 3rd edition of this book is out and it is pretty much the same as the 2nd edition.  If you are interested in the Azure Service Bus, there is a new chapter.  The new (3rd edition) book is still missing information for RESTful architectural design, so if you are looking for WCF REST look elsewhere.

 

  • Intro
  • Here Comes the 2nd Edition
  • Where and What is the New Content
    • Updated Syntax
    • Visual Studio 2008 Capabilities
    • WCF .NET 3.5 & .NET 3.5 SP1
    • ServiceModelEx Library
  • Where is the REST?
  • So what is in it for the Silverlight Developer?
  • Summary

 

Intro 

I have over 50 books in my technical library (This includes ONLY active ones, after over a decade or so in IT.  I have probably owned over 150 technical books and retired well over two-thirds of them).  However, rarely is there a resource/book that comes out that I have referenced again and again (not even mentioning re-reading).  A lot of these books I read mostly through.  Some I even re-read or went back to parts.  Very few of these books I considered a resource for a long time and went back to multiple times.  The main reason is that with the advent of the internet, lots of books become outdated almost as soon as they are in print.  A book has to be written really well and deliver insight that is hard to find elsewhere.  This article is dedicated to my favorite WCF resource.

WCF is one of the harder technologies to master properly.  It is an enterprise/business level technology that if you do not create these type of projects you will have very little exposure to the technology.  Furthermore, the technology is very powerful and demands a deep understanding in order to implement properly.  A lot of developers when looking to get started always look to Google to provide them with a good example from which to learn.  WCF is one of those technologies where trying to learn from an example or an article on the web is the wrong approach.  You could make that argument with every technology; however, when I started playing with Silverlight over a year ago or WPF, you can easily build on top of the knowledge you gain.   However, WCF is an enterprise level SOA platform that has so many intricacies and gotchas that you need to know about.  It makes trying to learn from a certain point (i.e., bindings, security, configuration) very hard.  I fell into this trap as well when I first started playing with WCF a little back in 2006.  I felt I was getting information in pieces and it was hard to grasp the overall concept or idea Microsoft was trying to convey with WCF.

How did I finally get my "aha" moment with WCF?  Almost 2 years ago I bought Programming WCF Services by Juwal Lowy.  This book is essentially an evolution of another great book by Juwal Programming .NET Components.  (It is all about coding in C# and utilizing component based architecture for design).  Out of all my technical books, this is one that I have consistantly read and referred back to multiple times.  Programming WCF Services is one of those books that reads like an "advanced placement physics book"; it gives you all the details and under-the-cover information.  However, having all the tools, you still need to think and implement the concepts yourself.  I absolutely love this type of format because it focuses less on trying to build examples or "tell" you how to code.  It covers most of the intricate topics with WCF (binding, configurations, security, reliable services, etc.) and allows you to make your own decisions on what is best for you.

Here Comes the 2nd Edition

Programming WCF Services was published on February 2007.  Therefore, a large majority of the book was written in 2006.  This is obviously before Visual Studio 2008, Silverlight, .NET 3.5, .NET 3.5 SP1, ADO.NET Data Services, LINQ, C# 3.0, etc., were all released.  Since then many new concepts were added to WCF in .NET 3.5 as well.  Furthermore, since 2006, the concept of REST-based services really picked up in adoption.   Furthermore, there is an increase of frameworks and best practices that have been vetted in large scale SOA deployments. Juwal Lowy updated his great book with a 2nd Edition and it is updated with all sorts of new information. The 2nd edition was officially released just a few weeks ago in October 2008.

The 2nd edition of Programming WCF Services has been updated with a lot of great new .NET 3.5 sp1 techniques that have been released since the first publication of the book.  I have both editions of the book.  First, you can see that the book is a little thicker.  Juwal mentioned the book was about 200 pages of extra content in an interview I heard over a month ago.  I don't know if anything changed, but the book does not have 200 extra pages of content.  The first edition of the book is 610 numbered pages.  The 2nd edition of the book is 750 numbered pages.  Obviously, doing the simple math, we now have an extra 140 pages.

You can see the 2nd Edition has noticably more content

140 pages more of WCF goodness

Where and What is the New Content

The book is organized the same way as the first edition of the book.  The chapters and their sequence between the two editions is identical.  Aside from several new additions to the Appendix, the overall structure of the book is the same.  So where is the new content?  The new content is well placed within the overall design of the book.  This is a great decision because of how well the book is laid out.  The book introduces the different parts that make up the WCF architecture very well and it enforces the concepts by adding to it.  For example, this is perfectly demonstrated when the topic of WCF object serialization is dicussed.  Juwal shows how you can do it using "traditional" .NET methods.  However, DataContracts are quickly introduced as the preferred method of serialization.  The concept of data contract serialization quickly becomes more complex with object inheritance, versioning, serializtion events and inferred contracts are introduced. As you can see, this is a real good way of building on a concept that might be new to even experienced developers.

Updated Syntax

As the concepts are introduced and built upon, Juwal introduces new C# 3.0 techniques, LINQ and lambda expressions into the various procedural code snippets and examples in the book.  This is really nice as you can see how much better these new techniques make working with WCF API easier.  LINQ and lambda expressions make their appearance in more than several examples in the book.  This is a real good way of seeing how these new techniques are more than just "syntax sugar" and really add value to programming.  You are also seeing how to utilize the new code from a software legend :)

Visual Studio 2008 Capabilities

WCF was introduced as part of the .NET 3.0 framework in 2006.  If you remember, this did not coincide with a new release of Visual Studio.  .NET 3.0 was an addition to .NET 2.0 and Visual Studio 2005.  Therefore, the tool support for WCF was not completely baked.  Visual Studio 2008 was released as part of the .NET 3.5 release and WCF has received enhanced support inside Visual Studio 2008.  Throughout the book screenshots and notes highlight on how to do certain functions relating to WCF in Visual Studio 2008.  Obviously this brings the 2nd edition to a much needed update as many developers have moved on to Visual Studio 2008.

WCF .NET 3.5 & .NET 3.5 SP1

WCF has been enhanced in several areas since it was introduced in .NET 3.0.  Some of the new .NET 3.5 WCF enhacements include ADO.NET Data Services, data contract serialization, REST support, WF integration and AJAX/Silverlight supported WCF services.  Unfortunately, the book only coveres all these new concepts minimally.  For example, the new data contract serialization in .NET 3.5 is covered in detail; however, most of the other new additions to WCF are completely omitted.  This is understandable as this would have added a lot more pages to the book and would have taken the book in a different direction.

ServiceModelEx Library

The book also includes descriptions and excerpts from the ServiceModelEx library.  This framework for WCF is on idesign's website and available for free.  The book does go over some of the ways you can use the framework to make the WCF programming easier.  While this is a nice addition, this was available for free for a while on the web site.  This code is peppered throughout the book; however, it is hard to tell if the code is part of the ServiceModelEx framework unless you check out the appendix.

Where is the REST?

This book is the BEST WCF self-paced resource on the market.  Having said that, this resource is missing one of the biggest trends in SOA design paradigms: Representational State Transfer (REST).  Well, isn't there probably is at least an excerpt about how REST should be avoided?  Wrong.  There is absolutely nothing in the book that I could find about REST at all.  This is completely inexcusable for several reasons.  REST is a valid enterprise service design.  Many of the largest service organizations are using REST APIs (i.e., Amazon, MySpace).  In fact, MySpace is based on WCF REST principles.  Some of the additions in .NET 3.5 such as URL re-writting were specifically added for REST design and are omitted in this resource.   REST design for "data-based" services is actually a lot more efficient (cachable, stateless, less chatty) than other WS* standards based WCF services.

I am not sure what Juwal Lowy's stance is on REST design.  If you find any interviews, podcasts or presentations online, you will probably hear Juwal's message that WCF deprecates the .NET programming model.  He makes a valid point that other software engineering principles rely on writing a lot of plumbing code. WCF programming (not just SOA) is a step in the direction of true design of software.  Essentially this is what REST design tries to do by embracing the web as for what it is and not try to "force" other designs into services.  This is why I think the omission of REST from the book is disappointing.

So what is in it for the Silverlight Developer?

There is actually very little here in terms of content strictly directed at the Silverlight developer.  As mentioned above, RESTful design and ADO.NET Data Services are not mentioned in the book.  This is a big dent for Silverlight developers as the only other WCF capabilities that are available are basicHttpBinding and duplex binding.  If you attended any of Juwal's, talks, he calls basicHttpBinding "brain dead" binding.  BasicHttpBinding is obviously not covered in real rigor in the book other than to say it is not recommended at all.  WS* standards based bindings are heavily recommended for the web.

Even with the limited coverage of some of Silverlight's key data access strategies, this book is an EXCELLENT resource for Silverlight developers.  As I mentioned above, this book reads like a physics book.  You do not have "direct content" strictly directed at the Silverlight developer.  However, the book builds a very solid foundation for WCF design.  If you go on the http://www.silverlight.net/ forums, you will see a majority of the questions for Silverlight are directed at either control examples or data access with Silverlight.  I think a lot of ASP.NET/Flash/Winforms developers are making the jump to Silverlight WITHOUT properly understanding WCF fundamentals.  You simply cannot design a data/service heavy application in Silverlight without understanding some very key Silverlight concepts.  From some of the basic questions being asked, you can see that Silverlight developers are struggling with the basics of WCF and what Silverlight supports for WCF.

This is why I believe that even though there is no Silverlight examples or best practices for Silverlight and WCF, this resource is invaluable for any serious Silverlight developer working with service-based data.  Before even STARTING a WCF based project, a developer needs to understand service contract design, contract serialization, WCF architecture (proxies, channels, interceptors), configuration (bindings, behavious), security (transport, message), etc.

Summary

In summary, if you want to learn about WCF or need a good WCF resource for a project, BUY this edition of this book.  This book is simply invaluable in how well it presents the information at a very high technical level.  The information has been updated for .NET 3.5 and includes over 140 pages of new content.  The content is presented extremely well and each topic builds on itself.  While it is disappointing that certain topics like REST have been omitted and there is no direct content for Silverlight developers, this book is still a great resource for any WCF developer.  Having said all that, this book is meant as a resource and reads like a college engineering book.  All the tools are laid out for you and how everything works including the gotchas; however, the solutions are missing [no simple plug in the numbers from an example here :)].

kick it on DotNetKicks.com
Posted: Nov 25 2008, 11:27 by Bart Czernicki | Comments (2) RSS comment feed |
  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Enterprise | WCF
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Silverlight clientaccesspolicy.xml files for the Enterprise (Part 1 of 2)

I decided to move this article up the chain in my backlog of articles as I have come across this scenario numerous times on the http://silverlight.net/ forums. This article will give some basic information that has been covered on numerous other sites and times and give some additional insight on how to handle cross-domain issues in enterprise Silverlight service deployments.

Note: This article is pretty long and doesn't really fit well into a blog format (which I find is very limited for effectivily presenting technical ideas on a larger scale).  I am going to start moving some of my bigger articles into possible whitepaper format as well.

Contents of this article (Part 1 of 2):

  • Background Information about cross-domain service access in Silverlight
  • Deploying cross-domain policy files on Enterprise Servers
    • Examples of Enterprise cross-domain configurations
    • Problems with maintaining the clientaccesspolicy.xml file manually
  • HttpHandler solution for dynamic clientaccesspolicy.xml files for the Enterprise
    • Walkthrough - Creating a basic HttpHandler for clientaccesspolicy.xml files
    • Basic Clientaccesspolicy Handler Part 1 - HttpHandler basics
    • Basic Clientaccesspolicy Handler Part 2 - Adding some code
  • Deploying managed HttpHandlers on IIS 7.0
    • Testing managed HttpHandlers (inside the browser)
    • TroubleShooting
  • Summary
  • Download link for HttpHandler source code

Background Information about cross-domain service access in Silverlight

Silverlight 2 uses services as its primary source of retrieving data across domain boundaries.  Once you enter the services and web application domain, you are exposing your content to malicious attacks.  One way Silverlight prevents its applications from launching malicious attacks on other sites is through opt-in cross-domain access.  This means the site has to say yes in order to receive and respond to requests from a particular domain.  This opt-in feature is controlled by a clientaccesspolicy.xml file.  If you have done any WCF programming with Silverlight, this should be familiar to you. If not, check the basic information on the MSDN site here.

Suppose that we have a Silverlight application hosted on  http://contoso.com/ (means the main/initial XAP file).  This application has a service backend that retrieves data from http://mycontososervice.com/.  These are obviously on two seperate domains and we have a cross-domain issue.  By default, this scenario will not work.  We need to create a clientaccesspolicy.xml file on the http://mycontososervice.com/ site that will allow calls from http://contoso.com/.  The location of the file must be located on the root of the site (http://mycontososervice.com/clientaccesspolicy.xml).

Here is a graphical representation of what is going on:

The clientaccesspolicy.xml file is located where the service is being hosted.  This is a very important point.  Most Silverlight developers that are starting out make a mistake in that they think the clientacesspolicy.xml is deployed onto the server where the Silverlight application is hosted.  This is not true and can cause many debugging headaches.  The clientacesspolicy.xml NEEDS to be deployed on the server hosting the WCF service so that Silverlight can properly consume it. 

Note: For simplicity reasons, I am not adding the crossdomain.xml file which is used by Flash.  Silverlight also uses this file in case the clientaccesspolicy.xml doesn't exist.  This is done for obvious reasons as Flash/Flex has a bigger install base and Silverlight is simply leveraging a possibly pre-existing cross-domain file.

 

Example of the format of the clientaccesspolicy.xml file that grants all domains access:

Example of the format of the clientaccesspolicy.xml file that grants access ONLY to contoso.com:

 Note: Notice how the only change was to add the <domain uri="http://contoso.com"/>.  This is more secure and other domains will be disallowed from making service calls.

Clientaccesspolicy.xml file that only grants service access from contoso.com (other requests are not fulfilled):

Deploying cross-domain policy files on Enterprise Servers

One of the key aspects of a clientaccesspolicy.xml file is that it needs to be accessed on the root of the website.  In our example above, the request is http://mycontososervice.com/clientaccesspolicy.xml.  In order to achieve this on IIS, we would simply place the clientaccesspolicy.xml file on the root of our website (default IIS: c:\inetpub\wwwroot folder).  If you want to grant multiple domains access, an admin simply can modify the clientaccesspolicy.xml file.

As mentioned above, Flash has an equivalent cross-domain configuration file to Silverlight called the crossdomain.xml file.  This file has a different format; however, it serves the same purpose as the Silverlight clientaccesspolicy.xml file.  Let's take look at how some of the largest companies based on services use this file.  You can try this yourself by using any browser.

Examples of Enterprise cross-domain configurations:

Example of the Amazon crossdomain.xml file (http://www.amazon.com/crossdomain.xml) :

Example of the MySpace crossdomain.xml file (http://www.myspace.com/crossdomain.xml):

Some notes to take away from the two examples above:

  • Root domains are different and this obviously makes the domain calls cross-domain.  (i.e., amazon.com != amazon.fr).  You need to list all the different domains
  • Sub domains also define cross-domain calls (i.e., lads.myspace.com != myspace.com).  You need to list the different sub domains.
  • Secure and unsecure (http vs. https protocols) also make the calls cross-domain.

As you can see, maintaining these files can get quite complex very quickly in more advanced scenarios.  These files need to be accurate and improperly formatted xml config files can cause the validation of the configuration to be invalidated.

Problems with maintaining the clientaccesspolicy.xml file manually

Maintaing the clientaccesspolicy.xml file manually on a single or even a couple of servers is not a problem.  However, maintaining complex properly validated clientaccesspolicy.xml files on multiple servers or domains can be quite challenging.  One single fat finger and the file can invalidate all service calls.  Improperly adding or not removing a domain can cause a serious security violation.

Scenarios where manually maintaining the clientaccesspolicy.xml file manually can be an issue:

  • You are maintaining 2 different RIAs and want to keep both XML files in sync (I know Silverlight can use Flash's file, but we want to prepare for mass Silverlight deployments) 
  • The clientaccesspolicy.xml file is complex.  You have over 10-15 domains, subdomains and protocols that all have to work.
  • The clientaccesspolicy.xml is dynamic
    • The solution you offer allows clients to access the site through specialized domain (i.e., client.mydomain.com, client2.mydomain.com)
    • Architecture/hosting uses SaaS model (You host services others can consume)
    • Lots of changes occur to the file and you want to eliminate the "human factor".
  • The web service server is part of a web server farm or a cluster.  The files need to be in sync almost instantaneously.
  • Client anonymity is important (i.e., You don't want to expose who is consuming your services)

Obviously some of these challenges can be mitigated with other security measures and designs.  However, let's assume that in your scenario you have a properly working architecture/deployment and the clientaccesspolicy.xml file is becoming a maintenance nightmare.  What can you do?

HttpHandler solution for dynamic clientaccesspolicy.xml files for the Enterprise

To overcome complex cross-domain scenarios by using some of the more advanced features of ASP.NET, we can mitigate some of the manual work that comes with creating cross-domain policy files.  HttpHandlers are one way to solve some of the problems I listed above.

Httphandlers are a pretty powerful tool for ASP.NET applications that extend ISAPI extensions.  There are many uses for Httphandlers and one of them is to map certain web requests to specific handler functionality.  (I am not going to go over handlers in detail.  If you need more information, try this link: http://www.15seconds.com/issue/020417.htm).  We can create an HttpHandler that will see a request for a clientaccesspolicy.xml file.  Instead of manually copying the file off of the root server, we can generate the file dynamically.

Walkthrough - Creating a basic HttpHandler for clientaccesspolicy.xml files

We are going to create a few sample handlers and add functionality to each one.

Basic Clientaccesspolicy Handler  Part 1 - HttpHandler basics

  1. Open Visual Studio 2008 and create a new project.
  2. Select "Class Library" and let's call the project "SilverlightCrossDomainHandler" (Note: Do NOT create a Silverlight Class library.)
  3. Add a reference to the System.Web assembly. (We are going to be creating an ASP.NET HttpHandler which requires the IHttpHandler interface found in the System.Web assembly)
  4. Add a new class to the project and call it BasicClientaccesspolicyHandler.cs.
  5. Navigate to the class and change its access modifier to be public.
  6. Add a using statement "using System.Web;".  (This is needed as we will be implementing the IHttpHandler interface.)
  7. Implement the IHttpHandler interface by simply typing ": IHttpHandler" after the BasicClientaccesspolicyHandler class name.
  8. Right-click on the IHttpHandler name and select Implement Interface -> Implement Interface.  This will create the methods we need to implement for this handler to work.

You should have something like this now:  (If not, simply just copy and paste the code from below)

  using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Web;  namespace SilverlightCrossDomain  {  public class BasicClientaccesspolicyHandler : IHttpHandler   {  #region IHttpHandler Members  public bool IsReusable  {  get { throw new NotImplementedException(); }  }  public void ProcessRequest(HttpContext context)  {  throw new NotImplementedException();  }  #endregion  }  }  

Basic Clientaccesspolicy Handler Part 2 - HttpHandler adding some code

  1. Change the getter for the IsResusable property the exception to simply "return true;" (This allows the Handler to be pooled.)
  2. Delete the "throw new NotImplementedException();" inside the ProcessRequest method.  We are going to replace this with code.  We are going to use LINQ in order to build the clientaccesspolicy.xml file.  We can just as easily use StringBuilder, XmlDocuments or other forms.  (This is NOT meant for production.  This is just illustrating a concept.)
  3. Add a reference to the System.Core assembly. (This houses the LINQ methods.)
  4. Add the following using statement: "using System.Xml.Linq;" .
  5. Copy and paste the code below and insert it into the ProcessRequest method.  The code below uses the Parse method from the XDocument class to load a string and transform it into an XDocument object.

            XDocument clientaccessPolicyDoc = XDocument.Parse(
            @"<?xml version=""1.0"" encoding=""utf-8""?>
            <access-policy>
              <cross-domain-access>
                <policy>
                  <allow-from http-request-headers=""*"">
                    <domain uri=""*""/>
                  </allow-from>
                  <grant-to>
                    <resource path=""/"" include-subpaths=""true""/>
                  </grant-to>
                </policy>
              </cross-domain-access>
            </access-policy>");

            context.Response.Write(clientaccessPolicyDoc.ToString());

Your class file should now look like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace SilverlightCrossDomainHandler
{
    public class BasicClientaccesspolicyHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            XDocument clientaccessPolicyDoc = XDocument.Parse(
            @"<?xml version=""1.0"" encoding=""utf-8""?>
            <access-policy>
              <cross-domain-access>
                <policy>
                  <allow-from http-request-headers=""*"">
                    <domain uri=""*""/>
                  </allow-from>
                  <grant-to>
                    <resource path=""/"" include-subpaths=""true""/>
                  </grant-to>
                </policy>
              </cross-domain-access>
            </access-policy>");

            context.Response.Write(clientaccessPolicyDoc.ToString());
        }

        #endregion
    }
}

Deploying managed HttpHandlers on IIS 7.0

This will go over deploying the HttpHandler solution we created above into IIS 7.0.  I wanted to provide some basic instructions on deploying handlers as it can be tricky, making this article a complete resource.  However, this article is not about deployment so I will cover only IIS 7.0.  Why IIS 7.0 and not 6.0?  Simply because I think that most advanced developers should be taking advantage of IIS 7.0 features and some of the new WCF 4.0 bits will only work in IIS 7.0.  If you haven't converted to developing on either Vista or Windows 2008 now is a good time to do so.

This is one way we can deploy the HttpHandler on our server.  I like this solution as it is a global way to add the handlers to the entire web server and it is simpler to follow.  There are several different ways to do this.  Another good solution would be to deploy the handlers with a Silverlight web project.  This way the clientaccesspolicy.xml handler is only enabled when a Silverlight application is deployed.

  1. Build the SilverlightCrossDomainHandler solution in release mode
  2. Sign the assembly so that we can deploy it to the GAC
  3. Install the assembly into the GAC by copying the assembly to the c:\windows\assembly\ folder
  4. Edit the web server web.config and add our assembly type
    1. Navigate to the C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\ folder (v2 because that is the last version that has hooks into the core ASP.NET assemblies....NET 3.0 and 3.5 simply build on top of this)
    2. Open the web.config file with Visual Studio
    3. In the compliation element there is an assemblies element with several assemblies listed.  We will add our custom assembly here.
    4. Add this element: <add assembly="SilverlightCrossDomainHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4d1c49f632a38a3c"/>
      1. Note: The PublicKeyToken could be different if you are doing this project on your own.  Simply copy it and replace it with whatever your assembly has been signed with.  You can check what your public key token is by right-clicking the assembly once it is in the GAC
    5. Save the web.config file
  5. Add the HttpHandler to the global web server
    1. Open up IIS Manager
    2. Double click on "Handler Mappings"
    3. There will be several listed that are pre-installed when ASP.NET and IIS are set up by default.  In order to add your own right-click and select "Add Managed Handler..." (this can take a few seconds)
    4. A dialog box will appear
      1. In the Request Path enter: clientaccesspolicy.xml (this will mean that ANY request to the clientaccesspolicy.xml file will be handled by our handler we choose)
      2. Select the SilverlightCrossDomainHandler and whatever type you want (i.e. BasicClientaccesspolicyHandler) from the dropdown menu (if it is not located there, you probably messed up editing the web.config file)
      3. Name the handler what you like (i.e. Clientaccesspolicyhandler)
      4. Perform a restart on the web server or an iisreset or restart the application pool

 

Testing managed HttpHandlers (inside the browser)

To test our deployment simply point your browser to http://localhost/clientaccesspolicy.xml.  Of course, you want to make sure that you actually do not have a clientaccesspolicy.xml file on the root of IIS. If you put the URL into the browser and click OK, you will simply get a blank page (as this is not an HTML/ASPX/RSS etc request that has a visual reponse).  You can either use Fiddler or Web Development Helper.  To test using the Web Development Helper (for those that use Fiddler, you know how to do this already):

  1. Install the tool, if you haven't done so already.  The tool is an add-in for Internet Explorer after you install it you have to close all your IE sessions.
  2. Go to Tools -> Web Development Helper
  3. A window shoul appear on the bottom
  4. Check Enable Logging (this will let you monitor any requests made from the browser)
  5. Navigate to the page hosting your handler (i.e. http://localhost/clientaccesspolicy.xml)
  6. You will see a row entry for the response from the server
  7. Double-click on the row and a dialog pops up with detailed information about the request
  8. Click the Response Content Tab and notice that we have a well formed clientaccesspolicy.xml file

Note on the screen shot that Enable Logging is checked.  We received a response from the request and the Response Contect is well formed for the clientaccesspolicy.xml and it is ready to serve us:

The fun doesn't stop here :)  Since we deployed the handler to handle ANY request anywhere for clientaccesspolicy.xml (which you may or may not want to do).  All requests for subdomains work fine as well and are handled by the very same handler we installed.  In my test case I created a sub domain and profiled and it works fine:

TroubleShooting

If you do not have the proper IIS ASP.NET and Extensibility add-ons (ISAPI) turned on, you might receive this error: (Simply go back to Add/Remove programs and add the ASP.NET and Extensibility features for IIS).  Furthermore, ensure that ASP.NET is properly registered on your site.

 

Summary

This article introduced you to some of the basics in managing a clientaccesspolicy.xml file for the Enterprise.  We looked at other cross domain files how they are published in Enterprise scenarios and how some scenarios could warrant a more dyanmic configuration file.  One way to solve the complexity of dynamic cross-domain configurations is to use HttpHandlers to create the configuration for us.  In part 1 of the series we created a simple HttpHandler that returned a well formed file.  In part 2 of the series, we will create a dynamic clientacesspolicy.xml file from a database store that will properly create the file in a more complex scenario.

SilverlightCrossDomainHandler.zip (18.51 kb)

 

kick it on DotNetKicks.com
Posted: Nov 08 2008, 15:32 by Bart Czernicki | Comments (1) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Enterprise | Silverlight | WCF
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us