Over coming Flex 2 sandbox security with .NET

Posted Thursday, February 16, 2006 12:59 AM by Shunjie
I created a RSS reader and a bookmark service that uses Del.icio.us in Flex 2. Everything goes well locally. However, once I upload it online, the sandbox security kicks in and nothing can be loaded. =X

I managed to solve this by creating a simple asp.net which loads the page for Flex. The code is simple

For Flex:

public class ServiceDelegate {
        public function getRemoteXML(url:String, listener:Function,
        username:String, password:String)
        {

            var urlloader:URLRequest = new URLRequest("http://<somedomain>.com/gateway.aspx");
            urlloader.method = "POST";
            var vars:URLVariables = new URLVariables();
            vars.serviceurl = url;
            if(username!= null) vars.username = username;
            if(password!=null)vars.password = password;
            urlloader.data = vars;
           
            var xmlloader:URLLoader =
            new URLLoader(urlloader);
            xmlloader.addEventListener(Event.COMPLETE,
            listener);
   
        }
    }

This function takes in the url, a callback function, a username and a password in the case authentication is needed, such as del.icio.us

On the asp.net side:

 protected void Page_Load(object sender, EventArgs e)
    {
        string serviceurl = Request.Form["serviceurl"];
        string username = Request.Form["username"];
        string password = Request.Form["password"];

        string result = "";
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(serviceurl);
        objRequest.Credentials = new System.Net.NetworkCredential(
              username, password);
        objRequest.PreAuthenticate = true;
        try
        {
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();       
            StreamReader sr = new StreamReader(objResponse.GetResponseStream());
            result =  sr.ReadToEnd();
            sr.Close();        
        }
        catch (Exception ex)
        {

        }      
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(result);
        Response.ContentType = "text/xml";
        this.Response.Write(doc.InnerXml);    
    }

With this, Flex 2 can now load from most pages without affecting sandbox security. Another approach is to use AJAX, although I have not tried it yet