5

我的目标是保护 aws s3 存储桶链接,我试图通过使用 cloudfront 作为可访问 s3 存储桶的链接来解决此问题,因此当用户尝试访问 cloudfront 链接时,如果有基本身份验证他们的浏览器中没有 cookie,但如果有 cookie,则检查此 cookie 中的身份验证值并授予用户访问权限。PS:这不是一个网站,我的任务是保护 s3 存储桶链接。

这是我的尝试,在查看器请求中使用 lambda@edge,如果用户未登录,则有身份验证页面,否则,他们被允许访问,它可以工作,但我无法设置 cookie,因为在 aws 文档的某个地方,云端删除头文件中的 set-cookies:CloudFront 从转发到您的源的请求中删除 Cookie 标头,并从返回给您的查看器的响应中删除 Set-Cookie 标头

这是我的代码:

'use strict';

// returns a response error
const responseError = {
                status: '401',
                statusDescription: 'Unauthorized',
                headers: {
                    'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
                }
};




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



    // checks to see if headers exists with cookies
    let hasTheHeader = (request, headerKey) => {
        if (request.headers[headerKey]) {
            return true;
        } 
        else return false;
    };

    // Add set-cookie header to origin response
    const setCookie = function(response, cookie) {
        const cookieValue = `${cookie}`;
        console.log(`Setting cookie ${cookieValue}`);
        response.headers['set-cookie'] = [{ key: "Set-Cookie", value: cookieValue }];    
    }


    // Configure authentication
    const authUser = 'someuser';
    const authPass = 'testpassword';
    let authToken;
    let authString;

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


    const authCookie = 'testAuthToken';

    //execute this on viewer request that is if request type is viewer request:
    if(event.Records[0].cf.config.eventType == 'viewer-request'){

        //check if cookies exists and assign authToken if it does not
        if(hasTheHeader(request, 'cookie')  ){
            for (let i = 0; i < headers.cookie.length; i++)
            {
                if (headers.cookie[i].value.indexOf(authString) >= 0)
                {
                    authToken = authString;
                    console.log(authToken);
                    break;
                }
            }
        }

        if (!authToken)
        {
                if (headers && headers.authorization && headers.authorization[0].value === authString)
                    {

                        // Set-Cookie: testAuthToken= new Buffer(authUser + ':' + authPass).toString('base64')



                        authToken = authString;
                        request.header.cookie = [];

                        //put  cookie value to custom header - format is important
                        request.headers.cookie.push({'key': 'Cookie', 'value': authString});

                    }
                else
                    {
                        callback(null, responseError);
                    }

                // continue forwarding request
                callback(null, request);
        }

        else{
            //strip out "Basic " to extract Basic credential in base 64
            var authInfo = authToken.slice(6);    

            var userCredentials = new Buffer(authInfo, 'base64');
            var userLoginNamePass = userCredentials.toString();

            var baseCredentials = userLoginNamePass.split(":");
            var username = baseCredentials[0];
            var userPass = baseCredentials[1];


            if (username != authUser && userPass != authPass) {

                //user auth failed
                callback(null, responseError);

            } else {

                request.header.cookie = [];

                //put  cookie value to custom header - format is important
                request.headers.cookie.push({'key': 'Cookie', 'value': authString});

            }

            // continue forwarding request
            callback(null, request);

        }

    }
    else if(event.Records[0].cf.config.eventType == 'origin-response')
    {

        if(hasTheHeader(request, 'cookie')){
            for (let i = 0; i < headers.cookie.length; i++)
            {
                if (headers.cookie[i].value.indexOf(authString) >= 0)
                {
                    setCookie(response, authString);
                    break;
                }
            }

        }

        // console.log(res_headers);
        console.log("response: " + JSON.stringify(response));
        callback(null, response);

    }
};

您的建议将非常受欢迎。提前致谢。

4

0 回答 0