且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用于提供私有文件​​的AWS S3实现

更新时间:2023-11-27 08:49:16

有两种使用Amazon S3的基本方法:

There are two basic ways to use Amazon S3:

  • 仅将其用作存储介质,只能由您的应用程序访问,或者
  • 使用它直接向最终用户提供内容

在第一种情况下,只有您的应用程序有权访问S3中存储的数据/文件.它必须检索内容并将其提供给用户.这是Web服务器的传统方法.

In the first case, only your application has access to the data/files stored in S3. It must retrieve the content and serve it to users. This is a traditional approach for web servers.

在第二种情况下,您可以生成HTML页面,这些页面包含对存储在S3中的文件的引用.例如,如果图像出现在网页中,则src=参数将指向Amazon S3 URL.然后,无需通过Web服务器即可从S3提供文件.

In the second case, you can generate HTML pages that contain references to files stored in S3. For example, if an image appears within a web page, the src= parameter would point to an Amazon S3 URL. The file is then served from S3 without going via your web server.

这可以通过使用预签名URL进行增强,这些URL是有时间限制的URL,可以访问存储在Amazon S3中的私有内容.它是这样的:

This can be enhanced by using Pre-Signed URLs, which are time-limited URLs that provide access to private content stored in Amazon S3. It works like this:

  • 文件存储在S3中,并保持私有状态(意味着不允许访问)
  • 您的应用程序完全负责确定哪些用户可以访问哪些文件
  • 当应用程序希望授予用户访问权限(例如,他们可能想要查看自己的照片)时,它会生成一个预签名URL,并将其包含在HTML页面中
  • 当用户的网络浏览器使用预签名URL"访问内容时
  • Amazon S3收到请求,验证预签名URL上的签名和时间戳,如果批准,则提供文件以响应该请求

一个预签名URL包含:

A Pre-Signed URL consists of:

  • 对请求的对象的引用
  • 与具有访问对象权限的IAM(身份和访问管理)实体关联的访问密钥-例如,您可以创建具有必要权限的IAM用户,然后为您的应用程序提供这些访问凭据
  • 到期时间戳,直到有效的预签名URL为止
  • 通过密码计算的签名,它验证预签名URL是由拥有访问密钥的实体创建的(有效地,它验证密码并散列上述信息)
  • A reference to the object requested
  • The Access Key associated with an IAM (Identity and Access Management) entity that has permission to access the object -- for example, you could create an IAM User that has the necessary permissions, and then provide these access credentials to your application
  • An expiry timestamp until which the Pre-Signed URL is valid
  • A cryptographically-calculated signature that verifies that the Pre-Signed URL was created by the entity that owns the Access Key (effectively, it verifies the password and hashes the above information)

仅需几行代码即可创建预签名URL,无需调用AWS API.

The Pre-Signed URL can be created in just a couple of lines of code and does not require a call to the AWS API.

底线:将所有图像设为不公开.您的应用程序确认每个用户有权即时访问图像,然后生成URL来授予有时间限制的访问.

Bottom line: Keep all images private. Your application confirms each user's right to access the images on-the-fly, then generates URLs to grant time-limited access.