Have you ever tried to read a RSS feed and been denied access? Or have you tried to read an XML file and for your code to throw up all manner of exceptions? Well with Silverlight 2 Microsoft decided to address the situation. The solution is a simple XML file called ClientAccessPolicy.xml. The Client Access Policy file allows you to grant access to Silverlight applications to access content on your server like RSS feeds, web services and WCF services.
Before jumping into the code make sure you read the following to ensure that you don’t have any conflicts.
When accessing a server (in this case for a RSS feed) Silverlight will automatically look for the Client Access Policy file. If the file exists then it will go by the configuration defined inside that. If the Client Access Policy file does not exist Silverlight by default looks for another file called Cross Domain (crossdomain.xml) which is the file format implemented by Adobe Flash. If the Cross Domain file exists then it will use its configuration settings and if both the Client Access Policy and the Cross Domain files do not exist then Silverlight will throw an exception.
For more information on the Cross Domain file please visit crossdomainxml.org.
When creating a Cross Access Policy file my advice would be to start with a file that allows full access to everything, test you code works and this fixes the problem. If you wish to lock it down then you can start tweaking it and testing your code to check there is no knock on effects. Below is the code to grant ‘full’ access.
To lock down the file you have several options but the main two are:
- <allow-from/> Defines the sites that are allowed to access resources in a certain policy.
- <grant-to/> Defines all the server’s resources that are affected by this policy.
To only allow certain sites to access your content list the sites domains in the <allow-from /> tags like below:
The above Client Access Policy will only allow access requests made from Silverlightforums.com or Silverlighttutorials.com and all other requests will be blocked. Requests from those two sites will be granted access to all content (including sub-directories).
The following Client Access Policy with allow access to all requests made from Silverlightforums.com but the only grant access to files inside the ‘feeds’ directory:
If you are comfortable with XML then setting up a Client Access Policy should be a breeze, but if you have any questions or need any help feel free to ask at Silverlight Forums.
Further information on the Client Access Policy can be found here at MSDN.