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

问题描述 投票:0回答:1

我有一个在www.mywebsite.com上运行的网站。这些文件与cloudFront一起托管在S3存储桶中。最近,我在网站上添加了一个新部分,该部分应该仅用于私有访问,因此我想在此进行某种形式的保护。但是,该网站的其余部分应保持公开状态。我的目标是使每个人都可以访问该站点,但是只要有人进入新部分,他们就不会看到任何源文件,并会提示输入用户名/密码组合。

新部分的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不包含我期望包含的内容,但是我似乎无法弄清楚其中包含了我所需的内容。

node.js security amazon-s3 aws-lambda amazon-cloudfront
1个回答
0
投票

我的猜测是request.uri不包含我期望包含的内容,但是我似乎无法弄清楚其中包含了我所需的内容。

[如果您使用的是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/")) {
© www.soinside.com 2019 - 2024. All rights reserved.