いろいろ備忘録

雑記です。

Node.jsでwsとExpressのセッションを共有する

const sessionMW = session({
//セッションIDの鍵
secret: 'aaaaaaaaaaaaaaaaaaaa',
//セッションの変更を自動で保存しない
resave: true,
//未初期化状態のセッションを保存しない
saveUninitialized: false,
//アクセス時に有効期限を延長しない
rolling: false,
//発行するクッキーの名前
name: "sessionInfo",
cookie: {
//jsからクッキーを読み込ませない
httpOnly: true,
//HTTPSでのみ送信する
secure: false,
//2時間で失効する
maxAge: 1000 * 60 * 60 * 2
}
});
app.use(sessionMW);
const verifyClient = (info, done) => {
sessionMW(info.req, {}, () => {
console.log(info.req.session);
if (typeof info.req.session.userid !== "undefined") {
console.log("セッションあった");
done(true);
} else {
console.log("session not found");
done(false, 401, "please login");
}
});
};
const wsServer = new ws.Server({
verifyClient: verifyClient,
server
});