Skip to content

Instantly share code, notes, and snippets.

@akirattii
Last active April 25, 2018 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/34aeef110d19ad116b5534fc82ba0413 to your computer and use it in GitHub Desktop.
Save akirattii/34aeef110d19ad116b5534fc82ba0413 to your computer and use it in GitHub Desktop.
ExpressJS: clientside secure cookie session example using `client-sessions`, which is faster than using any session-store and not required any database.
const express = require('express');
const app = express();
/**
* clientside cookie session.
* it's faster than using any express-session-store, and not required any database server ;)
*/
const sessions = require("client-sessions");
app.use(sessions({
cookieName: 'mySession', // cookie name dictates the key name added to the request object
secret: '<Enter_Your_Super_Strong_Secret_Key!!!!!>', // should be a large unguessable string
duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
activeDuration: 1000 * 60 * 5, // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
cookie: {
// path: '/', // cookie will only be sent to requests under '/api'
// maxAge: 60000, // duration of the cookie in milliseconds, defaults to duration above
ephemeral: true, // when true, cookie expires when the browser closes
httpOnly: true, // when true, cookie is not accessible from javascript
// CAUTION: NEVER forget to set **true** on production env for security reasons!:
secure: false, // when true, cookie will only be sent over SSL. use key 'secureProxy' instead if you handle SSL not in your node process
}
}));
app.get('/login', function(req, res) {
req.mySession.user = {
userId: Date.now(),
email: "foo@example.com",
status: 9999,
ipAddr: req.ip || req.connection.remoteAddress,
};
console.log("set cookie:", req.mySession);
res.send("set a new cookie session:" + JSON.stringify(req.mySession) + "<br>you can access to /");
});
app.get('/', function(req, res) {
console.log("req.mySession:", req.mySession);
// Simple spoofing bulletproof:
const currentIpAddr = req.ip || req.connection.remoteAddress;
if (req.mySession.user && req.mySession.user.ipAddr !== currentIpAddr) {
return res.status(400).send("Warning: Your IP address's changed!");
}
if (!req.mySession.user)
return res.send("please access to /login to set a new cookie.");
else
return res.send("welcome. your decoded cookie session data:" + JSON.stringify(req.mySession));
});
app.listen(3000, function() {
console.log('Example app listening on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment