URLRequest with HTTP authentication

I found a good explanation how to support HTTP authentication with URLRequests here.

That’s the most interesting part:

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.

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:

<?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).

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.

So this little code snippet explains the basics:

// Base64Encoder contained in Flex SDK
import mx.utils.Base64Encoder;
 
// Encode username and password
var base64Encoder : Base64Encoder = new Base64Encoder();        
    base64Encoder.encode( "username:password" );
 
// Create authorization request header
var urlRequestHeader : URLRequestHeader = new URLRequestHeader( "Authorization", "Basic " + base64Encoder.toString() );
 
// URLRequest setup
var urlRequest : URLRequest = new URLRequest( "url" );        
    // Needs to send some data!!        
    urlRequest.data = new URLVariables( "name=John+Doe" );        
    // Only supported with POST method!!        
    urlRequest.method = URLRequestMethod.POST;        
    // Apply authorization request header        
    urlRequest.requestHeaders = new Array( urlRequestHeader );

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.