I'm new to NodeJS. I am developing a REST API and using express-session to deal with sessions. So, to get the session ID I'm using
var sessionID = req.sessionID
This sessionID is generated from the server side. So, when I scale up to two or more servers, this is a problem. For example, if one server shuts down and the request is redirected to another server (Assuming I have a load balancer), a new session ID is generated. So, is there a way to retrieve the session ID from the client side?
Good question! Session management can be challenging to get up and running with - especially since to get up and running with any sort of sophisticated session management in node you need a ton of different packages, each with their own set of docs. Here is an example of how you can set up session management with MongoDB:
'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 + '.')
});
This configuration gives you access to req.sessionID but now it should persists across app servers if the user's session cookie has not expired.
I hope this works!
Related
I have created realm and client. keycloak json is placed in root folder. still i'm getting the error like,
Cannot read property 'keycloak-token' of undefined
TypeError: Cannot read property 'keycloak-token' of undefined at SessionStore.get (C:\Users\...\node_modules\keycloak-connect\stores\session-store.js:24:58)
var session = require('express-session');
var Keycloak = require('keycloak-connect');
var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({ store: memoryStore });
You get this error when you set app.use(keycloak.middleware()) and don't configure the session store. The keycloak-connect library is trying to read a keycloak-token value from the session that hasn't been configured. You can circumvent the error by supplying an Authorization header for example Authorization: Bearer 123 but the solution when using a session store is to configure it.
For a complete example see node_modules/keycloak-connect/example/index.js in your project's dependencies. A minimal example with resource protection using multiple middlewares in the route handler below.
Be advised however, that:
MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
const express = require('express')
const app = express()
const session = require('express-session');
const Keycloak = require('keycloak-connect');
var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({ store: memoryStore });
// Configure session
app.use(session({
secret: 'mySecret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));
// Attach middleware
app.use(keycloak.middleware());
// Attach route handler for home page
app.get('/', keycloak.protect(), (req, res, next) => {
res.json({status: 'ok'})
})
// Start server
app.listen(3005)
I'm working currently with one NodeJS + Express + Mongodb Applicacion and I need to get information stored in another monogodb database. So in my app.js file I'm doing the following steps in my app:
app.js
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
var passport = require('passport');
var configDB = require('./config/database.js');
// here I get the info from the Database IP and port.
mongoose.connect(configDB.url);
app.use( session({store: new MongoStore({mongoose_connection: mongoose.connections[0]}),
secret: 'secretPass',
cookie: {maxAge: 36000}, // session secret
saveUninitialized: true,
resave: true}
));
Is there a way to add another connection so I can use it so get information stored in the second database?
Thanks a Lot!
You can use the following code:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/database1'); // database connection
mongoose.connect('mongodb://localhost/database2');
I've been having problems trying to access stored session values! Once I've set the values and try access them from a new route, I get undefined! So basically I've got a login (POST) and in that request I set the session data, and then I have a show user details (POST) where I try and access the session data I've just stored.
Setup
// Setup express and needed modules #############################################
var express = require('express'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
redis = require("redis"),
redisStore = require('connect-redis')(session),
bodyParser = require('body-parser');
var client = redis.createClient(), //CREATE REDIS CLIENT
app = express();
// Setup app
app.use(cookieParser('yoursecretcode'));
app.use(session(
{
secret: 'x',
store: new redisStore({
port: 6379,
client: client
}),
saveUninitialized: true, // don't create session until something stored,
resave: false // don't save session if unmodified
}
));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.set('trust proxy', 1) // trust first proxy
So as you've seen my setup, you know I'm using express sessions and Redis. Below is where I'm setting the session values! If I print out the session values here it works, but then If I try and access the session data in another route it returns undefined.
Routes
I send a http post request and set the session data:
router.route('/login/').post(function(req, res) {
req.session.userId = req.body.uId;
req.session.name = req.body.uName;
// THIS PRINTS OUT IF I TRY AND ACCESS THE SESSION DATA HERE
console.log("THIS PRINTS OUT --> " + req.session.name);
});
So now that the session values have been set, I can go access them right, no, I get undefined each time I try and log them out.
router.route('/user/printoutuserdetails').post(function(req, res) {
// THESE RETURN UNDEFINED
console.log(req.session.userId);
console.log(req.session.uName);
console.log("THIS PRINTS OUT --> " + req.session.name);
});
Does anyone have any idea what's happening? I've tried everything and looked everywhere and can't seem to find a way to get it to work!
Solved:
The reason this wasn't was because you're not suppose to use sessions when using a RESTFUL api.
I have a simple, generic express app. It logs the req.sessionID whenever a certain route is hit. I would expect that refreshing the client page would result in the same sessionID being logged again. This works, if I've imported passport and added the passport middleware after the session middleware. If I either don't use passport at all, or I add passport middleware before the session middleware, then the sessionID is different every time.
I can accept that the ordering of middleware can be finicky. However, my app doesn't use passport at all, so I can't fathom why my app doesn't work if I don't require passport. Should passport be necessary for sessions to work?
//generic express initialization
var http = require('http');
var express = require('express');
var cookieParser = require('cookie-parser');
var passport = require('passport');
var session = require('express-session');
var app = express();
var server = http.createServer(app);
var sessionMiddleware = session({resave: false, saveUninitialized: false, secret: 'hunter2'});
app.use(cookieParser());
//This works:
app.use(sessionMiddleware);
app.use(passport.initialize());
//This doesn't:
app.use(passport.initialize());
app.use(sessionMiddleware);
Switch to resave: true, saveUninitialized: true
Unmodified sessions were not being saved, thus resulting in repeatedly generating new session IDs. Passport, however, was presumably doing some initialization on the session, meaning that the session was no longer unmodified.
Thanks to #Dodekeract and #Swaraj Giri for figuring the issue in their comments!
In node.js and express, there are many examples showing how to get session data.
Node.js and Socket.io
Express and Socket.io - Tying it all Together
Socket.io and Session?
As you can see when you visit the 3rd link, it's a link to StackOverflow. There was a good answer, but as pointed out in those comments by #UpTheCreek, connect no longer has the parseCookie method. I have just run into this problem as well. All of the tutorials I have found uses connect's parseCookie method which now doesn't exist. So I asked him how we can get the session data and he said he doesn't know the best approach so I thought I'd post the question here. When using express#3.0.0rc4, socket.io, and redis, how can we get session data and use that to authorize the user? I've been able to use require('connect').utils.parseSignedCookie;, but when I do that, I always get a warning/error when handshaking,
warn - handshake error Error
and from what I've read it sounds like that isn't a permanent solution anyways.
UPDATE
Ok I got session.socket.io working on my server. And as I suspected, I got stuck at the point of authorizing. I think I might be going about this the wrong way, so feel free to correct me. In my Redis database, I will have user's information. The first time that they login, I want to update their cookie so it contains their user information. Then the next time they come back to the site, I want to check if they have a cookie and if the user information is there. If it is not there, I want to send them to the login screen. At the login screen, when a user submits information, it would test that information against the Redis database, and if it matches, it would update the cookie with user information. My questions are these:
1) How can I update/change a cookie through RedisStore?
2) It looks like session data is saved only in cookies. How can I keep track of user information from page to page if someone has cookies turned off?
Here is my applicable code:
//...hiding unapplicable code...
var redis = require('socket.io/node_modules/redis');
var client = redis.createClient();
var RedisStore = require('connect-redis')(express);
var redis_store = new RedisStore();
var cookieParser = express.cookieParser('secret');
app.configure(function(){
//...hiding unapplicable code...
app.use(cookieParser);
app.use(express.session({secret: 'secret', store: redis_store}));
});
//...hiding code that starts the server and socket.io
var SessionSockets = require('session.socket.io');
var ssockets = new SessionSockets(io, redis_store, cookieParser);
io.configure(function(){
io.set('authorization', function(handshake, callback){
if(handshake.headers.cookie){
//var cookie = parseCookie(handshake.headers.cookie);
//if(cookie.user){
// handshake.user = cookie.user;
//}
}
callback(null, true);
});
});
ssockets.on('connection', function(err, socket, session){ ... });
Have a look at socket.io's wiki. Especially the parts Configuring Socket.IO and Authorization and handshaking.
It shows how to use socket.io with a RedisStore and gives two different authorization methods.
More information about connecting express v3, redis and socket.io
connect issue#588
socket.io and express 3
session.socket.io module
socket.io-express library
After switching to session.socket.io for a while I ran into a few problems due to the asynchronous nature of the module when loading the session information. So I ended up creating my own module called session.io. It is used like this:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
//Setup cookie and session handlers
//Note: for sessionStore you can use any sessionStore module that has the .load() function
//but I personally use the module 'sessionstore' to handle my sessionStores.
var cookieParser = express.cookieParser('secret');
var sessionStore = require('sessionstore').createSessionStore();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
//...truncate...//
app.use(cookieParser);
//make sure to use the same secret as you specified in your cookieParser
app.use(express.session({secret: 'secret', store: sessionStore}));
app.use(app.router);
});
app.get('/', function(req, res){
res.send('<script src="/socket.io/socket.io.js"></script><script>io.connect();</script>Connected');
});
server.listen(app.get('port'), function(){
console.log('Listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(server);
io.configure(function(){
//use session.io to get our session data
io.set('authorization', require('session.io')(cookieParser, sessionStore));
});
io.on('connection', function(socket){
//we now have access to our session data like so
var session = socket.handshake.session;
console.log(session);
});
Your questions:
How can I update/change a cookie through RedisStore?
It looks like session data is saved only in cookies. How can I keep track of user information from page to page if someone has cookies turned off?
Cookies / Sessions / RedisStore Thoughts:
Typically, you have exactly one cookie, which is the session id
All user-state is stored on the server in a "session" which can be found via the session id
You can use Redis as your back-end storage for your session data.
Redis will allow you to keep session state, even when your server is restarted (good thing)
You can store a mountain of data in your session (req.session.key = value)
All data stored in the session will be persistant until the user logs out, or their session expires
Example node.js Code:
var app = express.createServer(
express.static(__dirname + '/public', { maxAge: 31557600000 }),
express.cookieParser(),
express.session({ secret: 'secret', store: new RedisStore({
host: 'myredishost',
port: 'port',
pass: 'myredispass',
db: 'dbname',
}, cookie: { maxAge: 600000 })})
);
Session and Cookie Thoughts:
Your second issue us about sessions without cookies. This is possible.
You, basically, put the session id on the url of every request you send to the server.
I strongly believe that most people allow cookies.
If this is a requirement, google: "session without cookies"
Session data is available with:
req.session