Flex 3 – how to support HTTP Authentication URLRequest?

The syntax is a little different for URLRequest, but the idea’s the same:

private function doWork():void
{
    var req:URLRequest = new URLRequest("http://yoursite.com/yourservice.ext");
    req.method = URLRequestMethod.POST;
    req.data = new URLVariables("name=John+Doe");

    var encoder:Base64Encoder = new Base64Encoder();        
    encoder.encode("yourusername:yourpassword");

    var credsHeader:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + encoder.toString());
    req.requestHeaders.push(credsHeader);

    var loader:URLLoader = new URLLoader();
    loader.load(req);
}

A couple of things to keep in mind:

  • Best I can tell, for some reason, this only works where request method is POST; the headers don’t get set with GET requests.

  • Interestingly, it also fails unless at least one URLVariables name-value pair gets packaged with the request, as indicated above. That’s why many of the examples you see out there (including mine) attach “name=John+Doe” — it’s just a placeholder for some data that URLRequest seems to require when setting any custom HTTP headers. Without it, even a properly authenticated POST request will also fail.

  • Apparently, Flash player version 9.0.115.0 completely blocks all Authorization headers (more information on this one here), so you’ll probably want to keep that in mind, too.

  • You’ll almost surely have to modify your crossdomain.xml file to accommodate the header(s) you’re going to be sending. In my case, I’m using this, which is a rather wide-open policy file in that it accepts from any domain, so in your case, you might want to limit things a bit more, depending on how security-conscious you are.

crossdomain.xml:

<?xml version="1.0"?>
<cross-domain-policy>
    <allow-access-from domain="*" />
    <allow-http-request-headers-from domain="*" headers="Authorization" />
</cross-domain-policy> 

… and that seems to work; more information on this one is available from Adobe here).

The code above was tested with Flash player 10 (with debug & release SWFs), so it should work for you, but I wanted to update my original post to include all this extra info in case you run into any issues, as the chances seem (sadly) likely that you will.

Hope it helps! Good luck. I’ll keep an eye out for comments.

Leave a Comment