Synchromation - Code

Signing Amazon CloudFront REST Requests

Whilst creating signed REST requests for Amazon S3 services can be a complicated affair as detailed here, signing for CloudFront is a far simpler and can be performed by a simple category on NSMutableURLRequest.

Call the method just before sending a synchronous (or indeed asynchronous) request.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: cloudFrontURL];
[request signRequestForCloudFront];

@implementation NSMutableURLRequest (CloudFront)
- (void) signRequestForCloudFront
// Set Date header to date string in one of the RFC 2616 formats
// e.g. "Tue, 27 Mar 2007 21:06:08 +0000"
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat: @"EEE, d MMM yyyy HH:mm:ss zzzz"];
NSString *date = [dateFormatter stringFromDate:[NSDate date]];

[self addValue: date forHTTPHeaderField: @"Date"];

// For cloudfront the signature is calculated purely from the date sting only
NSString *signature = [self base64forData:[self HMACSHA1withKey: secretAccessKey forString: date]];

NSString *authorization = [NSString stringWithFormat:@"AWS %@:%@", accessKey, signature];

[self addValue: authorization forHTTPHeaderField: @"Authorization"];

Please note this snippet requires a Base64 encoder and the SHA-1 hashing code from All-Seeing's asi-http-request on GitHub