cloudfront
When developing a web application, you may decide to serve the landing page along with every static file through a CDN for better performance. CloudFront is a CDN offered by AWS that allows you to serve your content from different sources, known as origins, like S3 or a Load Balancer. Your application’s static files or dynamic data will be served through these origins to your users.
在开发Web应用程序时,您可能决定通过CDN随同提供到达页面以及每个静态文件,以提高性能。 CloudFront是AWS提供的CDN,允许您从不同的来源(称为来源,例如S3或负载均衡器)提供内容。 应用程序的静态文件或动态数据将通过这些来源提供给用户。
问题 (The Issues)
But during the development process of the application, you would need to host on AWS. Besides experimenting with different services on AWS, you would also need to create a staging or testing environment that can only be accessed by certain users.
但是在应用程序的开发过程中,您将需要托管在AWS上。 除了在AWS上试验不同的服务外,您还需要创建一个只能由某些用户访问的登台或测试环境。
In addition to that, as you may know, Google is constantly crawling the web and indexing the websites for user search queries, so you probably don’t want your staging environment to be indexed by Google and thus available to the world.
除此之外,您可能已经知道,Google一直在爬网并为用户搜索查询的网站编制索引,因此您可能不希望Google为您的暂存环境建立索引,并将其提供给全世界。
解决方案 (The Solution)
In that case, you would need a way to protect the content served through the CDN, and you can do that with an authentication method known as Basic Authentication. It is an authentication scheme built into the HTTP protocol that allows the users to access secured content by sending requests with a special Authorization
header that contains a base64
encoded version of a username and password to log in.
在这种情况下,您将需要一种方法来保护通过CDN提供的内容,并且可以使用称为“基本身份验证”的身份验证方法来做到这一点。 它是HTTP协议中内置的一种身份验证方案,允许用户通过发送带有特殊Authorization
标头的请求来访问受保护的内容,该标头包含base64
编码版本的用户名和密码进行登录。
An example is provided below:
下面提供了一个示例:
Authorization: Basic ZGVtbzpwQDU1dzByZA==.
This is the authorization dialog you get when you try to access a Basic Authorization-protected source:
当您尝试访问受基本授权保护的源时,将显示以下授权对话框:
![Image for post](https://img-service.csdnimg.cn/img_convert/d482fec6dca7cf004fbc01aa1d44de42.png)
输入Lambda @ Edge (Enter Lambda@Edge)
There is no direct method to apply Basic Authorization directly on CloudFront. However, it can be done by utilizing Lambda@Edge, which is a feature that allows you to execute logic before a request or after a response to your CloudFront distribution by adding different headers or checking the presence and validity of other request headers.
没有直接方法可以直接在CloudFront上应用基本授权。 但是,这可以通过利用Lambda @ Edge来完成,该功能使您可以通过添加不同的标头或检查其他请求标头的存在和有效性,在对CloudFront分配的请求之前或响应之后执行逻辑。
In our case, what you need is this: “Check whether a request made to the distribution contains the Authorization
header, and if it does, whether the base64
encoded value is the same as the encoded username-password combination.”
在我们的例子中,您需要的是:“检查对分发的请求是否包含Authorization
标头,如果包含,则base64
编码的值是否与编码的用户名-密码组合相同。”
The entire request lifecycle is illustrated in the following image:
下图说明了整个请求生命周期:
![Image for post](https://img-service.csdnimg.cn/img_convert/d9a134c3bff0dc4329d6b2a0af6e986c.png)
Once a request is made to the CloudFront distribution endpoint, Lambda@Edge will try to invoke a Lambda function that will analyze the request, extract the Authorization
header, and try to match the value of the header to the predefined username-password combination encoded with base64
encoding.
向CloudFront分发端点发出请求后,Lambda @ Edge将尝试调用Lambda函数,该函数将分析请求,提取Authorization
标头,并尝试将标头的值与使用编码的预定义用户名-密码组合进行匹配base64
编码。
If the header validation succeeds, the request goes through — it either returns data from the cache or retrieves the data from the origin and serves it. Otherwise, it returns an Unauthorized
response with status code 401.
如果头验证成功,则请求通过-它要么从缓存中返回数据,要么从源中检索数据并将其提供服务。 否则,它将返回状态码为401的Unauthorized
响应。
Lambda授权功能 (Lambda Authorization Function)
To make this work, you would first need to create a Lambda
function, which is given below:
为了使这项工作有效,您首先需要创建一个Lambda
函数,如下所示:
To keep it simple, you would define the username and password to be stored in memory. But if you want to have multiple users who can connect to this distribution, you would connect the Lambda
function to DynamoDB, where you would store the users and their passwords.
为了简单起见,您将定义要存储在内存中的用户名和密码。 但是,如果您希望有多个用户可以连接到此发行版,则可以将Lambda
函数连接到DynamoDB,以在其中存储用户及其密码。
The main logic resides in the header validation, where you validate whether the Authorization
header exists and if its value matches the basicAuthentication
value. basicAuthentication
is the variable where the base64
encoded value of the username-password combination is stored after it’s computed.
主要逻辑位于标头验证中,您可以在其中验证Authorization
标头是否存在以及其值是否与basicAuthentication
值匹配。 basicAuthentication
是在计算用户名-密码组合的base64
编码值后存储的变量。
In case the check fails, Lambda
returns a custom 401 Unauthorized
response by attaching www-authenticate
headers to inform the client about the type of the required authentication method.
万一检查失败, Lambda
通过附加www-authenticate
标头来向客户端通知所需的身份验证方法的类型,从而返回自定义401 Unauthorized
响应。
The second step is to allow this function to be triggered for every request made to the distribution. You would need to publish a new version of your Lambda
function (Actions -> Publish new version on the Lambda
menu) and copy the Lambda ARN
, along with its version. The Lambda ARN
should look like this:
第二步是允许对分发的每个请求触发此功能。 您将需要发布Lambda
函数的新版本(在Lambda
菜单上,选择Lambda
> Publish new version),然后复制Lambda ARN
及其版本。 Lambda ARN
应该如下所示:
arn:aws:lambda:us-east-1:ACCOUNT_NUMBER:function:basic_auth:1
Then you need to edit your CloudFront distribution’s behavior by associating the Lambda
function with a Viewer Request, as shown in the following image:
然后,您需要通过将Lambda
函数与查看器请求相关联来编辑CloudFront分配的行为,如下图所示:
![Image for post](https://img-service.csdnimg.cn/img_convert/ad5eab48e9f44306cfb860304de2cb2e.png)
This behavior will instruct Lambda@Edge to trigger the Lambda
function for every request made to the distribution.
此行为将指示Lambda @ Edge为对分发的每个请求触发Lambda
函数。
角色信任政策 (Role Trust Policy)
However, Lambda@Edge cannot trigger the function by default, as it doesn’t have any permissions to do that. When you create a Lambda
function, you are asked to either create an Execution Role or use an existing role for Lambda
. This role defines the principals that can execute the function. The default Execution Role can be assumed by the Lambda
service and has simple permissions for writing logs to CloudWatch.
但是,默认情况下,Lambda @ Edge无法触发该功能,因为它没有执行此操作的任何权限。 创建Lambda
函数时,系统会要求您创建执行角色或对Lambda
使用现有角色。 该角色定义了可以执行功能的主体。 Lambda
服务可以承担默认的执行角色,并且具有将日志写入CloudWatch的简单权限。
In our case, you would need Lambda@Edge to be able to assume that role and execute the function. For that reason, you need to specify the following trust policy for that execution role:
在我们的情况下,您将需要Lambda @ Edge能够承担该角色并执行该功能。 因此,您需要为该执行角色指定以下信任策略:
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": [ "lambda.amazonaws.com", "edgelambda.amazonaws.com" ] }, "Action": "sts:AssumeRole" }]}
With the trust policy in place, everything is set up for your distribution to be accessed only by trusted users.
有了适当的信任策略,所有设置都将设置为仅受信任用户可以访问您的分发。
You can apply Basic Authentication to a website or application when you would like to:
您可以在以下情况下将基本身份验证应用于网站或应用程序:
- Restrict access for certain users. 限制某些用户的访问。
- Restrict access for a staging or testing environment. 限制对暂存或测试环境的访问。
- Protect your website from being indexed by Google. 保护您的网站免遭Google索引。
结论 (Conclusion)
Thank you for reading this article. I hope you find it useful to implement in your projects.
感谢您阅读本文。 我希望您发现在项目中实施它很有用。
cloudfront