首页 > 解决方案 > 使用 Cloudfront 和 AWS Lambda 对 S3 托管网站进行身份验证时出现 503 错误

问题描述

我将以下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 来实现这个功能。谁能告诉我第一个功能有什么问题?

标签: amazon-web-servicesamazon-s3aws-lambdaamazon-cloudfrontbasic-authentication

解决方案


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

它应该是:

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

推荐阅读