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

编程入门 行业动态 更新时间:2024-10-04 21:15:26

AWS Lambda NodeJS:从参数存储中检索值并将其保存到<a href=https://www.elefans.com/category/jswz/34/1771380.html style=变量中"/>

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
回答如下:

更多推荐

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

本文发布于:2024-05-31 04:03:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771254.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   参数   并将其   AWS   Lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!