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

58wvjzkj  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(134)

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

'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
db2dz4w8

db2dz4w81#

我做了一点挖掘,发现下面的小修改使代码工作。在这里发布这个,以防将来有人遇到类似的问题:

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

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

    // Get request and request headers
    const request = event.Records[0].cf.request;
    const headers = request.headers;
    authPass = await getParam('/Path/ToPassword/EncryptedString');
    
    console.log("authUser : ", authUser);

    // 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);
};

const getParam = param => {
  return new Promise((res, rej) => {
    ssm.getParameter({
      Name : param,
        WithDecryption: true
    }, (err, data) => {
        if (err) {
          return rej(err)
        }
        return res(data.Parameter.Value)
    })
  })
}

相关问题