Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I missing about express sessions and cookies?

I've gotten pretty far with express and express-session and express-sql-session. I've got it creating a row in the database for a session when a user logs in. This is how I set it:

//login route handler
this.bcrypt.compare(password, row.hashed, function(err, passwordsMatch) {
    if (passwordsMatch === true) {
        console.log("user now logged in");
        req.session.user = row;
        req.session.success = 'User successfully logged in';
        res.send(row);
        res.end();
    }
});

Hunky dory! I can hop into my session table and get the row from the database. Here it is:

{"cookie":{"originalMaxAge":600000,"expires":"2015-08-24T23:16:20.079Z","httpOnly":false,"path":"/"},

"user":{"userID":24,"userName":"g","email":"g","joinDate":"2015-08-24T07:15:33.000Z"},"success":"User successfully logged in"}

Notice that you can see the custom use object is set. However, on the next request to get some data, I check for the user object on the session:

// some other route called after login. 
if (!req.session.user) {
    console.log('user not authorized' + JSON.stringify(req.session));
    res.send('not authorized');
    return;
}

but that logs an (apparently) empty session.

user not authorized{"cookie":{"originalMaxAge":600000,"expires":"2015-08-24T23:27:13.455Z","httpOnly":false,"path":"/"}}

Going into the browser, I also see no cookie is set in the resources panel. Shouldn't this be automatically generated with express 4 and session? The docs say you do not need expressCookie() with express 4 anymore. How do I get the correct session on subsequent requests?

Also, if I login again, it just creates a duplicate row in the sessions table. How do I properly set a cookie in the response to make this work for the next request?

Here's my session config if it helps:

// at the beginning of my node server 

import express = require('express');
import bodyParser = require('body-parser');
import Q = require('q');
import mysql = require('mysql');
var app = express();

import bcrypt = require('bcrypt');

import userModule = require('./userModule')
var UserRepository = new userModule.UserNamespace.UserRepository(connectToMySQL, bcrypt, Q );

import session = require('express-session');
var SessionStore = require('express-sql-session')(session);

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


var storeOptions = {
    client: 'mysql',
    connection: {
        host:SQLHOST,
        port:SQLPORT,
        user:SQLUSER,
        password: SQLPASS,
        database: SQLDB
    },
    table: SESSION_TABLE,
    expires: 365 * 24 * 60 * 60 * 1000
};

var sessionStore = new SessionStore( storeOptions );

app.use(session({
    secret: 'meeogog',
    resave: false,
    saveUninitialized: false,
    cookie: { maxAge: 600000,httpOnly: false },
    store: sessionStore
}));

... 

app.post('/users/login/', function (req, res) {
    UserRepository.loginHashed(req, res);
});

..and then more routes, and so forth
like image 511
FlavorScape Avatar asked Aug 24 '15 23:08

FlavorScape


People also ask

Why do we need sessions and cookies?

Session cookies allow websites to remember users within a website when they move between web pages. These cookies tell the server what pages to show the user so the user doesn't have to remember where they left off or start navigating the site all over again. Therefore, without session cookies, websites have no memory.

What is the difference between express session and cookie session?

This module stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.

How are sessions better than cookies?

Sessions are more secured compared to cookies, as they save data in encrypted form. Cookies are not secure, as data is stored in a text file, and if any unauthorized user gets access to our system, he can temper the data.

Do sessions require cookies?

Yes, Session management is done using a kind of session-id i.e. cookies. cookies maintained in the browser help backend to identify users.


1 Answers

Right after i bountied this i discovered that it was a combination of using localhost and not setting useCredentials on the xhr request. The localhost is what tripped me up you have to use the fully qualified 127.0.0.1 and to add to the headache, the http files are served on a different port, so had to change the wildcard to reflect that.

so...

//where the server runs on 127.0.0.1:3000 but the http runs from :9000
app.use(session({
    name:'some_session',
    secret: 'lalala',
    resave: true,
    saveUninitialized: false,
    cookie: { maxAge: 365 * 24 * 60 * 60 * 1000,httpOnly: false , domain:'127.0.0.1:9000'},
    store: sessionStore
}));


res.header("Access-Control-Allow-Origin", "http://127.0.0.1:9000");

//important
$http request (angular): useCredentials: true
like image 61
FlavorScape Avatar answered Sep 21 '22 12:09

FlavorScape