最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

AWS Lambda NodeJS:从参数存储中检索值并将其保存到变量中

网站源码admin27浏览0评论

AWS Lambda NodeJS:从参数存储中检索值并将其保存到变量中

AWS Lambda NodeJS:从参数存储中检索值并将其保存到变量中

我正在尝试创建一个 nodeJs 应用程序,它从 AWS 参数存储中获取加密字符串并将其用作基本访问身份验证(基于用户名和密码的身份验证)的密码。但是出于某种原因(可能是 nodeJs 的异步行为),我无法将值正确分配给全局变量,如下面的代码和 stakc trace 所示:

'use strict';
const AWS = require('aws-sdk');
const ssm = new AWS.SSM({region: 'us-east-1'});
var authPass = 'default';
let authUser = 'user';

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

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

    getParameterFromSystemManager( 
        (data) => {
            authPass = data;
            console.log('Inside func authPass : ', authPass); //This is where the printed value is 'password2' i.e. actual expected string
        }
    );
    
    console.log("Outside function call : ", authPass);  //This is where the printed value is 'default' when it should be password2

    // 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);
    }
    callback(null, request);
};


function getParameterFromSystemManager(callback) {
    var params = {
        Name: '/Path/ToPassword/EncryptedString',
        WithDecryption: true
    };
    ssm.getParameter(params, function(err, data) {
        if (err) {
            console.log(err, err.stack); // an error occurred
        } else {
            callback(data.Parameter.Value);
        }
    });
}

从上面可以看出,主要的认证功能有2个控制台日志。当我测试 lambda 函数时,这是我收到的输出:

Function Logs
START RequestId: 7d2eaccf-f064-4a5b-94c2-f8ff666dxxxx Version: $LATEST
2023-05-18T00:21:13.937Z    7d2eaccf-f064-4a5b-94c2-f8ff666dxxxx    INFO    Outside function call :  default
2023-05-18T00:21:14.177Z    7d2eaccf-f064-4a5b-94c2-f8ff666dxxxx    INFO    Inside func : data password2 authPass password2
END RequestId: 7d2eaccf-f064-4a5b-94c2-f8ff666dxxx
REPORT RequestId: 7d2eaccf-f064-4a5b-94c2-f8ff666dxxxx  Duration: 676.17 ms Billed Duration: 677 ms Memory Size: 128 MB Max Memory Used: 81 MB  Init Duration: 503.74 ms
回答如下:
发布评论

评论列表(0)

  1. 暂无评论