I am trying to get the secret for express-session from AWS parameter store. This doesn't seem to create a session, there are no errors but I can't log in.
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 };
CodePudding user response:
You're not supposed to call session({...})
over and over. You're supposed to call it once, then save that result and use that as middleware. When you call it over and over again, you keep making new instances of the object that manages your sessions and thus they don't connect to previous sessions.
I'd suggest changing to something like this:
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
});
This would be cleaner to code in an ESM module with top level await
.
Or here's another way to implement that's a little more like you originally had:
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")
});