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

标签 node.js security amazon-s3 aws-lambda amazon-cloudfront

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

新部分的 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/")) {

关于node.js - 如何使用 AWS Lambda 中的完整请求 URL 仅在某些页面上执行逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59653061/

相关文章:

Javascript xmlhttp 获取对 nodejs 服务器的请求不返回任何内容

java - Android Id 及其可靠性

python - 解密AWS S3中的对象而不将其下载到本地系统

javascript - 如何使用 handlebar helpers 打印 JSON 对象

javascript - Node.js SELECT*FROM SQL 数据库中的表

.net - 我什么时候需要 .NET 中的 SecureString?

android - Android如何保证安全性?

amazon-s3 - 带有 postman 的 AWS S3 预签名 URL 上传图像

hadoop - 在集群部署模式下运行 spark 提交作业失败但通过客户端

javascript - NodeJs, Spawn 转换