如何在没有Amazon Cognito的情况下使用AWS S3?

时间:2022-11-19 09:22:29

I am using a Node.js REST API to authenticate my users. Once they are authenticated I allow them to post photos with text. My plan is to store the text and the URL to the photo in the database. That way when they go to the feed of posts, my app will query the database to get the text and URL's and then use all of the URL's to get the images from S3 directly. Is this the correct way to do it and if so how come I can not do so without using cognito. I am trying to cut costs and it seems like cognito would be useless since I already add authentication with my API.

我正在使用Node.js REST API来验证我的用户。一旦他们通过身份验证,我就允许他们发布带有文字的照片。我的计划是将文本和URL存储到数据库中的照片中。这样,当他们转到帖子的源时,我的应用程序将查询数据库以获取文本和URL,然后使用所有URL直接从S3获取图像。这是正确的方法,如果是这样的话,如果不使用cognito,我怎么也不能这样做。我正在努力削减成本,因为我已经使用我的API添加身份验证,因此认知似乎是无用的。

Here is the code I have thus far.

这是我到目前为止的代码。

    let S3BucketName = "*******"

    // configure authentication with Cognito
    let CognitoPoolID = "*************"
    let Region = AWSRegionType.USEast1
    let credentialsProvider = AWSCognitoCredentialsProvider(regionType:Region,
                                                            identityPoolId:CognitoPoolID)
    let configuration = AWSServiceConfiguration(region:Region, credentialsProvider:credentialsProvider)
    AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

    let ext = "png"
    let imageURL = NSBundle.mainBundle().URLForResource("iimage", withExtension: ext)!

    let uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest.body = imageURL
    uploadRequest.key = NSProcessInfo.processInfo().globallyUniqueString + "." + ext
    uploadRequest.bucket = S3BucketName
    uploadRequest.contentType = "image/" + ext

    let transferManager = AWSS3TransferManager.defaultS3TransferManager()
    transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
        if let error = task.error {
            print("Upload failed (\(error))")
        }
        if let exception = task.exception {
            print("Upload failed (\(exception))")
        }
        if task.result != nil {
            let s3URL = NSURL(string: "http://s3.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")!
            print("Uploaded to:\n\(s3URL)")
        }
        else {
            print("Unexpected empty result.")
        }
        return nil
    }

3 个解决方案

#1


7  

For without cognito use this in

因为没有认知使用这个

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    AWSStaticCredentialsProvider *credentialsProvider = [[AWSStaticCredentialsProvider alloc] initWithAccessKey:AWS_ACCESS_KEY secretKey:AWS_SECRET_KEY];

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

    AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
}

and for uploading image use

并用于上传图像使用

AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];

AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = AWS_S3_BUCKET_NAME;
uploadRequest.key = @"cards/image.png";
uploadRequest.contentType = @"image/png";
uploadRequest.body = imageURL;

[[transferManager upload:uploadRequest] 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
                                                           {
                                                               // Unknown error.
                                                               NSLog(@"Error: %@", task.error);
                                                           }
                                                       }

                                                       if (task.result)
                                                       {
                                                           AWSS3TransferManagerUploadOutput *uploadOutput = task.result;
                                                            NSLog(@"success: %@", uploadOutput);
                                                       }
                                                       return nil;
                                                   }];

#2


0  

One easy way to accomplish this is to have your server generate a presigned URL and send that URL back to the mobile app. An example if your server is written in Java is http://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLJavaSDK.html . All of the AWS SDKs support generating a presigned URL if your server is in another language.

实现此目的的一种简单方法是让您的服务器生成预签名URL并将该URL发送回移动应用程序。如果您的服务器是用Java编写的,请参见http://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLJavaSDK.html。如果您的服务器使用其他语言,则所有AWS开发工具包都支持生成预签名URL。

This way your AWS credentials need only be on your server, and after you have authenticated your users you can give them back the URL for access (which will expire after a set period of time).

这样,您的AWS凭证只需要在您的服务器上,并且在您对用户进行身份验证后,您可以向他们返回访问URL(在一段时间后过期)。

Keep in mind if you do end up needing to authenticate with AWS down the road that the Cognito Identity APIs are free.

请记住,如果您最终需要使用AWS进行身份验证,那么Cognito Identity API是免费的。

#3


-2  

AWS S3 allows unauthenticated users. You still have to set up an account, obtain a bucket, and set policies (permissions).

AWS S3允许未经身份验证的用户。您仍然需要设置帐户,获取存储桶以及设置策略(权限)。

Go to this link and review the services policies. You'll want to look at IAM and S3.

转到此链接并查看服务政策。你想看看IAM和S3。

I am adding an edit. Hopefully this helps:

我正在添加一个编辑。希望这会有所帮助:

Use the following:

使用以下内容:

    AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = @"bucket name";  
uploadRequest.key =  fileName;
uploadRequest.body = url;  //This is a temporaryURL for the file stored at your client.  

AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];

// Execute the request 
[[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task)
{ 
    if (task.error)
    {
        // do something
    }
    else
    {
        // do something
    }

}];

The S3 bucket has local policies so that you can set it up to allow unauthenticated users; you are charged for the storage, of course, if the user abuses this access.

S3存储桶具有本地策略,因此您可以将其设置为允许未经身份验证的用户;当然,如果用户滥用此访问权限,则需要为存储付费。

#1


7  

For without cognito use this in

因为没有认知使用这个

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    AWSStaticCredentialsProvider *credentialsProvider = [[AWSStaticCredentialsProvider alloc] initWithAccessKey:AWS_ACCESS_KEY secretKey:AWS_SECRET_KEY];

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

    AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
}

and for uploading image use

并用于上传图像使用

AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];

AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = AWS_S3_BUCKET_NAME;
uploadRequest.key = @"cards/image.png";
uploadRequest.contentType = @"image/png";
uploadRequest.body = imageURL;

[[transferManager upload:uploadRequest] 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
                                                           {
                                                               // Unknown error.
                                                               NSLog(@"Error: %@", task.error);
                                                           }
                                                       }

                                                       if (task.result)
                                                       {
                                                           AWSS3TransferManagerUploadOutput *uploadOutput = task.result;
                                                            NSLog(@"success: %@", uploadOutput);
                                                       }
                                                       return nil;
                                                   }];

#2


0  

One easy way to accomplish this is to have your server generate a presigned URL and send that URL back to the mobile app. An example if your server is written in Java is http://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLJavaSDK.html . All of the AWS SDKs support generating a presigned URL if your server is in another language.

实现此目的的一种简单方法是让您的服务器生成预签名URL并将该URL发送回移动应用程序。如果您的服务器是用Java编写的,请参见http://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLJavaSDK.html。如果您的服务器使用其他语言,则所有AWS开发工具包都支持生成预签名URL。

This way your AWS credentials need only be on your server, and after you have authenticated your users you can give them back the URL for access (which will expire after a set period of time).

这样,您的AWS凭证只需要在您的服务器上,并且在您对用户进行身份验证后,您可以向他们返回访问URL(在一段时间后过期)。

Keep in mind if you do end up needing to authenticate with AWS down the road that the Cognito Identity APIs are free.

请记住,如果您最终需要使用AWS进行身份验证,那么Cognito Identity API是免费的。

#3


-2  

AWS S3 allows unauthenticated users. You still have to set up an account, obtain a bucket, and set policies (permissions).

AWS S3允许未经身份验证的用户。您仍然需要设置帐户,获取存储桶以及设置策略(权限)。

Go to this link and review the services policies. You'll want to look at IAM and S3.

转到此链接并查看服务政策。你想看看IAM和S3。

I am adding an edit. Hopefully this helps:

我正在添加一个编辑。希望这会有所帮助:

Use the following:

使用以下内容:

    AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = @"bucket name";  
uploadRequest.key =  fileName;
uploadRequest.body = url;  //This is a temporaryURL for the file stored at your client.  

AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];

// Execute the request 
[[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task)
{ 
    if (task.error)
    {
        // do something
    }
    else
    {
        // do something
    }

}];

The S3 bucket has local policies so that you can set it up to allow unauthenticated users; you are charged for the storage, of course, if the user abuses this access.

S3存储桶具有本地策略,因此您可以将其设置为允许未经身份验证的用户;当然,如果用户滥用此访问权限,则需要为存储付费。