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

huangapple go评论72阅读模式
英文:

AWS Lambda NodeJS : Retrieve a value from parameter store and save it into a variable

问题

以下是您提供的代码的翻译部分:

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

'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) => {

    // 获取请求和请求头
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    getParameterFromSystemManager(
        (data) => {
            authPass = data;
            console.log('Inside func authPass : ', authPass); // 这里打印的值应为 'password2',即预期的实际字符串
        }
    );

    console.log("Outside function call : ", authPass); // 这里打印的值应为 'password2',但实际上是 'default'

    // 构造基本身份验证字符串
    const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');

    // 需要基本身份验证
    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); // 发生错误
        } else {
            callback(data.Parameter.Value);
        }
    });
}

您提到的输出表明,在主要的身份验证函数中有2个控制台日志。当我测试Lambda函数时,这是我收到的输出。

英文:

I am trying to create a nodeJs app that gets an encrypted string from the AWS parameter store and uses it as a password for basic access authentication (username and password based authentication). For some reason though (probably asynchronous behaviour of nodeJs), I'm unable to assign the values correctly to the global variable as can be seen in the below code and 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);
}
});
}

As it can be seen above that the main authentication function has 2 console logs. When I test the lambda function this is the output that I receive :

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

答案1

得分: 0

我进行了一些调查,并发现以下细微更改使代码能够运行。在这里发布,以防将来有其他人遇到类似问题:

'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) => {

    // 获取请求和请求标头
    const request = event.Records[0].cf.request;
    const headers = request.headers;
    authPass = await getParam('/Path/ToPassword/EncryptedString');
    
    console.log("authUser : ", authUser);

    // 构造基本身份验证字符串
    const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');
    
    
    // 要求基本身份验证
    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)
    })
  })
}
英文:

I did a little digging and found that the following minor changes make the code work. Posting this here just in case somebody else has a similar issue in the future :

'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)
})
})
}

huangapple
  • 本文由 发表于 2023年5月18日 08:58:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定