Skip to content
Advertisement

session value is not stored properly

I am using express-session and express-mysql-session in my app to generate sessions and store them in mysql database. Sessions are stored in a table called sessions.

const express = require('express');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const cookieParser = require('cookie-parser');

const connection = {
  host: process.env.MYSQL_HOST,
  port: process.env.MYSQL_PORT,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
};

const sessionStore = new MySQLStore(connection);

module.exports = app => {
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(
    session({
      name: 'sessID',
      secret: 'someSecret',
      resave: false,
      store: sessionStore,
      saveUninitialized: true,
    })
  );

Sessions are stored in table but the value of it is not as same as the session value in client-side or console. Example: decoded value in client-side and console is s:fiNdSdb2_K6qUB_j3OAqhGLEXdWpZkK4.eKUawMNIv7ZtXSweWyIEpfAUnfRd6/rPWr+PsjuGCVQ, However the value that is stored is fiNdSdb2_K6qUB_j3OAqhGLEXdWpZkK4. It’s not complete, I have no idea what is happening.

SHOW CREATE TABLE sessions:

sessions    CREATE TABLE `sessions` (
`session_id` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin 
 NOT NULL,
 `expires` int unsigned NOT NULL,
 `data` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,
 PRIMARY KEY (`session_id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci 

Advertisement

Answer

The value that’s stored on the client-side cookie consists of two parts:

  1. The actual session ID (fiNdSdb2_K6qUB_j3OAqhGLEXdWpZkK4 in your example)
  2. A server-generated HMAC signature of the session ID eKUawMNIv7ZtXSweWyIEpfAUnfRd6/rPWr+PsjuGCVQ. This is to ensure session ID integrity and does not need to be stored in the database. It’s generated on the server-side by express-session (which uses node-cookie-signature package internally) and using the passed secret parameter.

So the second part of the cookie name (after the dot) is used by express-session to verify the first part and is stripped away afterward.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement