我试图从AWS参数存储中获取express-session的秘密。这似乎没有创建会话,没有错误,但我无法登录。
const param = require('./param');
const ssecret = param.getSecret('ss');
app.use(async (req, res, next) => {
const sessionSecret = await ssecret;
session({
proxy: true,
secret: sessionSecret,
resave: false,
saveUninitialized: true,
cookie: { secure: true }
})(req, res, next);
console.log("TEST")
});
param.js
const AWS = require("aws-sdk");
const ssm = new AWS.SSM({ region: "us-east-1" });
const getSecret = async (ss) => {
console.log(`Getting secret for ${ss}`);
const params = {
Name: ss,
WithDecryption: true
};
const result = await ssm.getParameter(params).promise();
return result.Parameter.Value;
};
module.exports = { getSecret };
您不应该一遍又一遍地调用session({...})
。您应该调用它一次,然后保存该结果并将其用作中间件。当你一次又一次地调用它时,你会不断地创建管理会话的对象的新实例,因此它们不会连接到以前的会话。
我建议改成这样:
const param = require('./param');
param.getSecret('ss').then(sessionSecret => {
app.use(session({
proxy: true,
secret: sessionSecret,
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
// other initialization of app here
});
在具有顶级await
的ESM模块中编写代码会更简洁。
或者这里有另一种实现方式更像你最初的方式:
let sessionMiddleware;
app.use(async (req, res, next) => {
const sessionSecret = await ssecret;
if (!sessionMiddleware) {
sessionMiddleware = session({
proxy: true,
secret: sessionSecret,
resave: false,
saveUninitialized: true,
cookie: { secure: true }
});
}
sessionMiddleware(req, res, next);
console.log("TEST")
});