4

I have this Node API that frontends a backend OAuth server. At the end of the SAML OAuth dance, I set the Bearer Token in a browser cookie.

// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());

// set a cookie
app.use(function (req, res, next) {
  // check if client sent cookie
  var cookie = req.cookies.cookieName;
  if (cookie === undefined)
  {
    // no: set a new cookie
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
    console.log('cookie created successfully');
  } 
  else
  {
    // yes, cookie was already present 
    console.log('cookie exists', cookie);
  } 
  next(); 
});


app.use(express.static(__dirname + '/public'));

Now I was introduced to a fancy NPM which does pretty much the same thing https://github.com/mozilla/node-client-sessions

While I was almost inclined on using this NPM, I bumped into express-session. https://github.com/expressjs/session - this is for server side sessions. But this also sets a cookie

    var express = require('express');
    var session = require("express-session");
    var app = express();


    app.use(session({
        resave: true,
        saveUninitialized: true,
        secret: 'ABC123',
        cookie: {
            maxAge: 60000
        }
    }));


    app.get("/test", function(req, res) {
        req.session.user_agent = req.headers['user-agent'];
        res.send("session set");
    });

If my need to set only a bearer token in the browser cookie for subsequent API calls, which option should be my choice?

lonelymo
  • 3,972
  • 6
  • 28
  • 36

1 Answers1

9

express-session is my go to.

If you look at what it took to accomplish the same thing with the two different methods, I think the answer is clear.

If all you want to do is set a client cookie that will enable the server to correctly authenticate future requests, express-session is awesome.

Here is an example set from another question I answered that uses MongoDB as a backend to store your sessions:

'use strict';

var express = require('express'),
  session = require('express-session'),
  cookieParser = require('cookie-parser'),
  mongoStore = require('connect-mongo')(session),
  mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/someDB');

var app = express();

var secret = 'shhh';

app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secret,
  store: new mongoStore({
    mongooseConnection: mongoose.connection,
    collection: 'sessions' // default
  })
}));

// ROUTES, ETC.

var port = 3000;

app.listen(port, function() {
  console.log('listening on port ' + port + '.')
});
Community
  • 1
  • 1
Huston Hedinger
  • 511
  • 2
  • 9
  • And the session will be matched automatically in each and every subsequent API call? GET POST alike? – lonelymo Oct 01 '15 at 06:34
  • 1
    Yes, exactly. On incoming requests, express-session looks for the `connect.sid` cookie, and then attaches the session to `req.session`. Notice how `session` is being defined inside of `app.use(...)`. Session acts as a middleware. – Huston Hedinger Oct 01 '15 at 07:52