AWS API网关提供了一个安全的端点来暴露Lambda函数,同时还提供了可以在API网关和Lambda之间对数据进行传输加密的选项。
一种简单的方法是通过使用HTTPS与API网关进行通信来加密数据传输。为了确保此选项生效,需要将API Gateway部署到一个具有公共SSL/TLS证书(例如,通过AWS Certificate Manager)的域名。
以下是一个使用Node.js和AWS SDK for JavaScript V3构建的Lambda函数示例,其中API网关与Lambda之间的请求使用HTTPS进行传输:
const AWS = require('aws-sdk');
const https = require('https');
const agent = new https.Agent({
keepAlive: true,
maxSockets: 50,
rejectUnauthorized: true
});
exports.handler = async (event) => {
const apiGatewayEndpoint = process.env.API_GATEWAY_ENDPOINT;
const apiGatewayPath = '/my-api-endpoint';
const queryStringParams = 'param1=value1¶m2=value2';
const apiGatewayMethod = 'GET';
const httpOptions = {
agent: agent,
headers: {
'Content-Type': 'application/json'
}
};
const apiGatewayURL = `https://${apiGatewayEndpoint}${apiGatewayPath}?${queryStringParams}`;
const req = https.request(apiGatewayURL, httpOptions, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
req.on('error', (err) => {
console.error(`Error making request: ${err}`);
});
req.end();
return {
statusCode: 200,
body: JSON.stringify('Success')
};
};
在此示例中,使用https.Agent将保持HTTP(S)连接,maxSockets指定了最大并发连接数,rejectUnauthorized将强制客户端验证SSL证书,从而使HTTPS连接更加安全。