如何在 AWS Lambda 中使用完整请求 URL 仅在特定页面上执行逻辑

How to use the full request URL in AWS Lambda to execute logic only on certain pages

我在 www.mywebsite.com 上有一个网站 运行。这些文件与 cloudFront 一起托管在 S3 存储桶中。最近,我在网站上添加了一个新部分,它应该只供私人访问,所以我想在那里设置某种形式的保护。但是,站点的其余部分应保留 public。我的目标是让每个人都可以访问该站点,但是一旦有人访问新部分,他们就不应该看到任何源文件,并且会提示输入 username/password 组合。

新部分的 URL 例如 www.mywebsite.com/private/index.html ,...

我发现 AWS Lambda 函数(node.js)对此很有用,而且它有点管用。我已经设法验证了整个网站中的所有内容,但我无法弄清楚如何让它只在包含完整 URL 名称的例如“/private/*”的页面上工作。我编写的 lambda 函数如下所示:

'use strict';

exports.handler = (event, context, callback) => {


// Get request and request headers
const request = event.Records[0].cf.request;
const headers = request.headers;

  if (!request.uri.toLowerCase().indexOf("/private/") > -1) {
      // Continue request processing if authentication passed
     callback(null, request);
     return;
  }

// Configure authentication
const authUser = 'USER';
const authPass = 'PASS';

// Construct the Basic Auth string
const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');

// Require Basic authentication
if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) {
    const body = 'Unauthorized';
    const response = {
        status: '401',
        statusDescription: 'Unauthorized',
        body: body,
        headers: {
            'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
        },
    };
    callback(null, response);
}

// Continue request processing if authentication passed
callback(null, request);
};

不起作用的部分是以下部分:

     if (!request.uri.toLowerCase().indexOf("/private/") > -1) {
      // Continue request processing if authentication passed
     callback(null, request);
     return;
  }

我的猜测是 request.uri 不包含我期望的内容,但我似乎无法弄清楚哪些包含我需要的内容。

My guess is that the request.uri does not contain what I expected it to contain, but I can't seem to figure out what does contain what I need.

如果您使用的是 Lambda@Edge 函数(看起来是)。然后你可以在这里查看请求事件结构:https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html#lambda-event-structure-request

您可以使用 console.log 并检查 Cloudwatch 中的相应日志来查看请求 URI 字段的实际值。

问题可能出在这一行:

if (!request.uri.toLowerCase().indexOf("/private/") > -1) {

如果您要严格检查 JavaScript 字符串中是否包含另一个字符串,您可能想要这样做:

if (!request.uri.toLowerCase().indexOf("/private/") !== -1) {

或者更好的是,使用更现代的 JS:

if (!request.uri.toLowerCase().includes("/private/")) {