使用accesskey和secretkey从S3服务器下载安全文件

时间:2015-08-20 06:31:16

标签: ios amazon-web-services amazon-s3

我尝试使用NSURLSessionDownloadTask从S3服务器下载安全文件,但它返回403错误(拒绝访问)。
我的代码:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://xxx.amazonaws.com/bucket-name/file_name"]];
request.HTTPMethod = @"GET";

[request setValue:@"kAccessKey" forHTTPHeaderField:@"accessKey"];
[request setValue:@"kSecretKey" forHTTPHeaderField:@"secretKey"];

NSURLSessionDownloadTask *downloadPicTask = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    UIImage *downloadedImage = [UIImage imageWithData:
                                [NSData dataWithContentsOfURL:location]];
    dispatch_async(dispatch_get_main_queue(), ^{
        weakSelf.imageView.image = downloadedImage;
        [weakSelf.activityIndicator stopAnimating];
    });

}];
[downloadPicTask resume];

修改

我找到了这段代码:

AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc]initWithRegionType:AWSRegionUSWest2 identityId:@"xxxxxxx" identityPoolId:@"xxxxxxxx" logins:nil];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc]initWithRegion:AWSRegionUSWest2 credentialsProvider:credentialsProvider];

// Construct the NSURL for the download location.
NSString *downloadingFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"sample_img.png"];
NSURL *downloadingFileURL = [NSURL fileURLWithPath:downloadingFilePath];

// Construct the download request.
AWSS3TransferManagerDownloadRequest *downloadRequest = [[AWSS3TransferManagerDownloadRequest alloc]init];
AWSS3TransferManager * transferManager = [AWSS3TransferManager S3TransferManagerForKey:[[configuration credentialsProvider]sessionKey]];

downloadRequest.bucket = @"test-upload-bucket";
downloadRequest.key = @"sample_img.png";
downloadRequest.downloadingFileURL = downloadingFileURL;

[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor]
                                                       withBlock:^id(AWSTask *task){
                                                           return nil;
                                                       }];

IdentityId和IdentityPoolId的输入值是什么?

3 个答案:

答案 0 :(得分:5)

2017年夏季工作功能,您可以传递图像名称和表格单元格(我正在下载某些表格条目的徽标)。确保修改凭据区域,密钥/机密凭据以及存储桶名称。注意:您的凭据不应该是root。创建单独的IAM用户/组/策略,仅授权特定资源(存储桶/对象)和特定操作。创建你的密钥和秘密。我这样做了,因为我不想用亚马逊的cogito来管理我的用户。但希望我的移动应用程序直接安全地访问S3资源,而不是通过一些冗余的服务器端脚本。但是,亚马逊建议使用移动设备,您使用cogito并让每个用户使用自己的/临时信用卡。注意事项。

-(void) awsImageLoad:(NSString*)imageFile :(UITableViewCell*)cell  {

NSArray *filepathelements = [imageFile componentsSeparatedByString:@"/"];
if (filepathelements.count == 0) return;

//extract only the name from a possibe folder/folder/imagename
NSString *imageName = [filepathelements objectAtIndex:filepathelements.count-1];

AWSStaticCredentialsProvider *credentialsProvider =
[[AWSStaticCredentialsProvider alloc]
 initWithAccessKey:@"_______________"
 secretKey:@"__________________________________"];

//My credentials exist on the US East 1 region server farm
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc]initWithRegion:AWSRegionUSEast1 credentialsProvider:credentialsProvider];

// Construct the NSURL for the temporary download location.
NSString *downloadingFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:imageName];

NSURL *downloadingFileURL = [NSURL fileURLWithPath:downloadingFilePath];

// Construct the download request.
AWSS3TransferManagerDownloadRequest *downloadRequest = [AWSS3TransferManagerDownloadRequest new];

// S3 has only a Global Region -- establish our creds configuration
[AWSS3TransferManager registerS3TransferManagerWithConfiguration:configuration forKey:@"GlobalS3TransferManager"];

AWSS3TransferManager * transferManager = [AWSS3TransferManager S3TransferManagerForKey:@"GlobalS3TransferManager"];

downloadRequest.bucket = @"my_bucket_name";
downloadRequest.key = imageFile;
downloadRequest.downloadingFileURL = downloadingFileURL;

[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task){

    if (task.error){
        if ([task.error.domain isEqualToString:AWSS3TransferManagerErrorDomain]) {
            switch (task.error.code) {
                case AWSS3TransferManagerErrorCancelled:
                case AWSS3TransferManagerErrorPaused:
                    break;

                default:
                    NSLog(@"Error: %@", task.error);
                    break;
            }
        } else {
            NSLog(@"Error: %@", task.error);
        }
    }

    if (task.result) {
        // ...this runs on main thread already
        cell.imageView.image = [UIImage imageWithContentsOfFile:downloadingFilePath];
    }
    return nil;
}];
}

答案 1 :(得分:1)

在发送到AWS服务器之前,所有HTTP请求都需要正确签名,签名过程非常复杂Signature Version 4 Signing Process所以我建议尝试AWS Mobile SDK for iOS v2

Arun_显示的示例是如何使用transferManager通过AWS Mobile SDK for iOS v2下载文件的代码片段。

答案 2 :(得分:0)

这对我有用:

    AWSStaticCredentialsProvider *credentialsProvider = [[AWSStaticCredentialsProvider alloc]initWithAccessKey:@"AccessKey" secretKey:@"secretKey"];



    AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc]initWithRegion:AWSRegionUSWest2 credentialsProvider:credentialsProvider];

    // Construct the NSURL for the download location.
    NSString *downloadingFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"sample_img.png"];
    NSURL *downloadingFileURL = [NSURL fileURLWithPath:downloadingFilePath];

    // Construct the download request.
    AWSS3TransferManagerDownloadRequest *downloadRequest = [AWSS3TransferManagerDownloadRequest new];
   [AWSS3TransferManager registerS3TransferManagerWithConfiguration:configuration forKey:@"USWest2S3TransferManager"];
    AWSS3TransferManager * transferManager = [AWSS3TransferManager S3TransferManagerForKey:@"USWest2S3TransferManager"];
    downloadRequest.bucket = @"test-upload-bucket";
    downloadRequest.key = @"sample_img.png";
    downloadRequest.downloadingFileURL = downloadingFileURL;

    [[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor]
                                                           withBlock:^id(AWSTask *task){
                                                               return nil;
                                                           }];