使用Cloudfront和AWS Lambda for S3托管的网站进行身份验证时出现503错误

时间:2019-04-18 06:40:21

标签: amazon-web-services amazon-s3 aws-lambda amazon-cloudfront basic-authentication

我将以下 AWS Lambda功能 CloudFront 相关联,以向在 Amazon S3 中托管的静态网站添加身份验证>,for循环的问题,如果我针对单个用户名和密码进行测试,则可以正常工作;如果添加多个凭据,则会出现503错误。

    exports.handler = (event, context, callback) => {
    // Get request and request headers
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    // Configure authentication
    const credentials = {

        'admin1': 'passadmin2',
        'user1': 'passuser1',
        'admin2': 'passadmin2',
        'user2': 'passuser2'
    };


    let authenticated = true;
    //verify the Basic Auth string
    for (let username in credentials) {
        // Build a Basic Authentication string
        let authString = 'Basic ' + Buffer.from(username + ':' + credentials[username]).toString('base64');
        if (headers.authorization[0].value == authString) {
            // User has authenticated
            authenticated = true;
        }
    }


    // Require Basic authentication
    if (typeof headers.authorization == 'undefined' || !authenticated) {
        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);
};

使用一个用户名和密码,就可以正常工作:

示例:

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

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

      // Specify the username and password to be used
      const user = 'admin1';
      const pw = 'passadmin1';

      // Build a Basic Authentication string
      const authString = 'Basic ' + new Buffer(user + ':' + pw).toString('base64');

      // Challenge for auth if auth credentials are absent or incorrect
      if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) {
        const response = {
          status: '401',
          statusDescription: 'Unauthorized',
          body: 'Unauthorized',
          headers: {
            'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
          },
        };
        callback(null, response);
      }

      // User has authenticated
      callback(null, request);
    };

我正在为此功能使用nodejs 8和typescript。 谁能告诉我第一个功能出了什么问题?

1 个答案:

答案 0 :(得分:3)

您正在检查headers.authorization[0]而不检查它是否未定义:

应该是:

...
        if (headers.authorization && headers.authorization[0].value == authString) {
            // User has authenticated
            authenticated = true;
        }
...