SecurityException when making requests to websites in Silverlight 2.0

by Dominic Zukiewicz 17. November 2008 12:48

The 3 types of connections Silverlight can make are:

  • Connections to web services and WCF services
  • HTTP requests (via HttpWebRequest and WebClient)
  • Raw data transfers

When building one of your early applications, you may choose to try out one of these classes to get back a really simple piece of HTML, purely to test the connection. For example:

protected void Button_Click(object sender, EventArgs e)
{
    WebClient wc = new WebClient("http://www.google.com");    
    wc.DownloadStringAsyncCompleted += new EventHandler<DownloadStringEventArgs>(wc_DownloadStringCompleted);    
    wc.DownloadStringAsync();
}

protected void wc_DownloadStringCompleted(object sender, DownloadStringEventArgs e)
{
    if(e.Error == null && e.Cancelled == false)  
    {        
        Debug.WriteLine("Data downloaded = " + e.Result);    
    }
}

(N.B I apologise if this doesn't compile, I've just typed this by hand.)

If you run this, you'll find it generates a SecurityException, but why?

To improve security, the only connections you can make without any security implications is your own website. If you want to call another website, Silverlight needs to check a few things. Firstly, it looks for a policy file called "clientaccesspolicy.xml", which is a file used by Adobe Flash to find out if it allows connections from Flash applications. If this file is missing, it then looks for "crossdomain.xml", which is a Silverlight version of this file.

  • If one of these exists AND the policy file allows connections, then the application will be allowed to connect.
  • If neither exists, or the policy in an existing file denies access to the requested virtual directory, then a SecurityException will be thrown by the application.

To overcome this problem, you have 2 options

  1. Check the website has an API to use the capabilities you are after. Google and Digg have service APIs in order to allow applications to do this.
  2. Write a web service (or WCF service), that does the enquiry for you.

If you need to see the contents of these files, I have found Fiddler an excellent tool for this purpose.

Tags:

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar