首页 > 解决方案 > 如何在 iOS 上处理带有 .m3u8 文件的 CloudFront 签名 Cookie?

问题描述

我有一个应用程序正在播放存储在 AWS 上的音频文件。音频内容由 AWS CloudFront 签名的 cookie 功能保护。我在创建签名 cookie 并将它们设置在原始 HTTP 请求中没有问题AVURLAsset,并且对于 .mp3 内容一切正常。不过,在访问 .m3u8 文件时,我收到 403 HTTP 错误。我注意到初始请求正常并且 .m3u8 文件已正确下载,但后续请求(针对音频片段)不起作用并收到 403,因为未发送 cookie。

我已经尝试过使用NSHTTPCookieStorage,但它不起作用;-(

NSURL *url = [NSURL URLWithString: @"http://..../stream.m3u8"]

// Get the Cookie Storage
NSHTTPCookieStorage *cookiesStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

// Create the array to store the cookies
NSMutableArray *cookies = [NSMutableArray array];

// Create the Cloud-Front-Policy Cookie
NSHTTPCookie *cloudFrontPolicyCookie = ... 
[cookies addObject:cloudFrontPolicyCookie];

// Create the Cloud-Front-Signature Cookie
NSHTTPCookie *cloudFrontSignatureCookie = ... 
[cookies addObject:cloudFrontSignatureCookie];

// Create the Cloud-Front-Key-Paid-Id Cookie
NSHTTPCookie *cloudFrontKeyPairIdCookie = ... 
[cookies addObject:cloudFrontKeyPairIdCookie];

// Create the HTTP Header Dictionary
NSMutableDictionary * headers = [NSMutableDictionary dictionary];

// I omitted the cookie creation, but it is ok! I tested using curl on the command line 
NSString *cookieAsHeader = ... 

// Set the header
[headers setObject:cookieAsHeader forKey:@"Cookie"];

// Create the AVURLAsset so that I can use the headers and the cookies
// Notice that I tried using only the headers (which works)!
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:url options:@{@"AVURLAssetHTTPHeaderFieldsKey": headers, AVURLAssetHTTPCookiesKey : [cookiesStorage cookies] }];

// For secured .mp3 files, it works just fine
// but for .m3u8, the content does not play as the first file part receives 403. Notice that the first request (for the .m3u8) works just fine. 
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];

标签: iosswiftobjective-cavplayer

解决方案


您需要生成 cookie,不幸的是 aws ios sdk 没有此功能。我现在的临时解决方案是以下之一:

1) 要求 Web 服务器生成 cookie(使用 aws php sdk)。通过这种方式,您可以在几分钟或任何您需要的时间设置超时,这样您就可以保证数据的安全。

2) 在代码中硬编码cookies。您可以使用 aws php sdk 在本地生成它,然后将持续时间设置为尽可能长。可能一年或更长时间取决于您的状况。但是,如果有人可以看到它,您的数据将被暴露。

3) 在 swift/obj-c 中创建我们自己的 cookie 生成器函数。我们可以使用 aws php sdk 作为参考。


推荐阅读