expressjs / cookie-session Goto Github PK
View Code? Open in Web Editor NEWSimple cookie-based session middleware
License: MIT License
Simple cookie-based session middleware
License: MIT License
I want my user's session cookie to be updated every time they interact with the site, but cookie-session will only update the cookie if the contents has changed. From the documentation it seems that the overwrite option is designed to allow the cookie to be updated which each request.
This would allow the us to set a semi-short expiration time and update it with every interaction without needing to change the contents of the cookie. The only work around I've been able to come with right now is to write another property containing a new Date() object with each request, but this feels very hack-y-ish to me.
In the code, cookie-session reads in the overwrite option, but then just ignores it when deciding whether or not to right the cookie. The overwrite option seems to just be ignored in the code altogether. I guess it gets passed to the cookies module with all of the other options, but the behavior is ignored in the native session-cookie code.
This may not be a bug, but just me not knowing what to do.
So I want to update my session cookie everytime my users to an api call and he/she has ticked the "remember me" checkbox on login. So far, I have been able to update the expiry on the express:sess cookie just fine. Now my issue is I cannot update the expiry of my express:sess.sig cookie. When my user quits his/her browser, the express:sess.sig cookie disappears and my user will no longer have a valid session (even though he/she still has the express:sess cookie)
Am I doing something fundamentally wrong here?
In your docs you say this: "Other options are passed to cookies.get() and cookies.set() allowing you to control security, domain, path, and signing among other settings."
Where do we actually change what cookies.set() does? Maybe its in cookies.set() where I should add 7 days to the expiry?
The latest version is not actually in NPM.
Whenever I try to install the latest alpha version with npm the package.json file gets updated with "cookie-session": "^2.0.0-alpha.1"
but the code belongs to 1.2.0
npm install cookie-session --save
Also, it would be nice to have a version number in the file. I had to use a code comparison tool to realise the version was not the correct one.
RFC 6265 (http://tools.ietf.org/html/rfc6265#section-4.1.1) specifies the cookie name as token that is defined in RFC 2616 (http://tools.ietf.org/html/rfc2616#section-2.2) which specifies:
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
So just removing the colon from the default name would be fine.
Hi again. I have the following problem: I've changed session cookie path from default '/' to '/test'.
app.use(session({
resave: true,
name: 'test.connect.sid',
keys: ['key1', 'key2'],
secret: 'testsecret',
secure: false,
domain: 'localhost',
path: '/test'
}));
My /test1 route sets test string to the session.
app.get('/test1', function(req, res, next) {
req.session.test = 'test';
res.redirect('http://localhost:3000/test2');
});
Before redirect I have a test string in request session, but after redirect to '/test2' request session is undefined.
app.get('/test2', function(req, res, next) {
console.log('test2', req.session.test); // undefined
res.send(req.session.test);
});
When session cookie path is default ('/') all works as expected. But I need a different cookie paths.
May be you know how to fix it?
cc @dougwilson @jonathanong I emailed github staff and this is no longer a fork.
How can I decidee whether to save cookies or not based on a req.body property for example remember_me checkbox?
Error: Cannot find module 'cookie-signature'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/embrujado/projects/expressjs4/node_modules/express-session/index.js:15:17)
...
In express3.x this was possible using req.session.cookie.maxAge
.
However it seems that req.session.cookie is undefined. So is it possible to change the properties of the cookie without changing them globally?
How do I set the maxAge
property on the cookies/sessions that get created? jed/cookies only provides "expires" as a date.
Keys are provided in the example, but not documented. It would be good to make clear what options are required to make cookie-session secure.
It's me again :)
Maybe i do something wrong, but default settings still not working.
Here is the code:
var cookieSession = require('cookie-session');
app.use(cookieParser());
app.use(cookieSession({
name: 'session',
secret: 'dexter',
cookie: {
secure: true,
httpOnly: true,
maxAge : 1111
}
})
);
app.get('/login', function(req, res, next) {
req.session.someid = 'bar';
res.render('login');
});
And there is chrome developers-tool(F12/Network):
Connection:keep-alive
Cookie:session=eyJycnIiOiJkc3NzcyIsInRlc3QiOiJkc3NzcyIsImZvbyI6ImJhciIsInNvbWVpZCI6ImJhciJ9; session.sig=RoXWvswDSKg8qoZS5ePtVn1jl3Q
maxAge is not set to 1111 :(
What i do wrong?
I'm trying to use _cookie-session_ with _express.io_ and so avoid using _MemoryStore_
This is my code :
express = require('express.io');
app = express().http().io();
require('express.io-middleware')(app);
app.use(express.cookieParser());
var session = require('cookie-session');
app.use(express.session({secret: 'hygdfreiliu'}));
app.io.use(function(req, next) {
if (req.session.user || (req.io.event === "user:login")) {
try {
next();
}
catch(err){
__debug.error('REQUEST_ERROR');
var result = new (require("./core/result.js"))();
result.notification.error("#REQUEST_ERROR");
req.io.respond(result);
}
}
});
An exception occurs:
TypeError: object is not a function
at /home/dev/svn/webmail2/node_modules/express.io/compiled/index.js:107:20
at iterate (/home/dev/svn/webmail2/node_modules/express.io/node_modules/async/lib/async.js:108:13)
at Object.async.forEachSeries (/home/dev/svn/webmail2/node_modules/express.io/node_modules/async/lib/async.js:124:9)
at Manager.<anonymous> (/home/dev/svn/webmail2/node_modules/express.io/compiled/index.js:106:24)
at Manager.authorize (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:925:31)
at Manager.handleHandshake (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:801:8)
at Manager.handleRequest (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:616:12)
at Server.<anonymous> (/home/dev/svn/webmail2/node_modules/express.io/node_modules/socket.io/lib/manager.js:119:10)
at Server.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
How can i avoid this problem ?
I am using cookie-session and the cookie does not get created on it its own when i browse any page in my web app.
Code -
var cookieSession = require('cookie-session')//http://goo.gl/IImRVj
var cookieParser = require('cookie-parser');
app.use(modules.cookieParser());// read cookies (needed for auth)
app.use(modules.cookieSession({
name: 'session',
keys: ['mysecretty'],
maxAge : 365 * 24 * 60 * 60 * 1000
}))
However a cookie of name "session is created when i add this line -
app.use(function(req, res, next) {
req.session.foo = 'bar';
next();
});
I do not use livereload in my web app
Hello,
Just executing the sample code you provide I cannot access the cookie options via req.sessionOptions
.
For instance: if I am going to use it via a simple REST API to authenticate browsers' users I don't know if their cookie expired and how to request a new one.
Thanks
For all matters, this is the code I am using to check it:
var cookieSession = require('cookie-session')
var express = require('express')
var app = express()
app.set('trust proxy', 1) // trust first proxy
var opt = {
name: 'session',
keys: ['key1', 'key2'],
// maxAge: 24 * 60 * 60 * 1000, // 24 hours
expires: new Date(new Date().getTime() + 1*60000) // 30 minutes
};
console.log(JSON.stringify(opt))
app.use(cookieSession(opt))
app.get('/', function (req, res, next) {
// Update views
req.session.views = (req.session.views || 0) + 1
console.log(req.sessionOptions)
// if (req.sessionOptions.expires < new Date().getTime()) {
console.log('session: ' + JSON.stringify(req.session))
res.end(req.session.views + ' views') // Write response
// }
// else {
// req.session = null
// }
})
app.listen(3000)
The docs say that Session.isNew is "true" when the session is new. I've tried all of the following:
var session = require('cookie-session');
...
app.use(session({
keys: ['key1', 'key2']
}));
app.use(function (req, res, next) {
var isNew = Session.isNew; // ReferenceError: Session is not defined
var isNew = session.isNew; // undefined
var isNew = req.session.isNew; // undefined
...
}
Where do I find this elusive isNew
flag?
I didn't manage to remove the session after the browser gets closed.
My initialization:
app.use(cookieSession({
maxAge: 8*60*60*1000, //8 hours
httpOnly: true,
secure: false,
secureProxy: true,
keys: ['key1', 'key2']
}));
expires: a Date object indicating the cookie's expiration date (expires at the end of session by default).
When using express 4.1.1, the cookie session middleware does not seem to be able to set the set-cookie header. For example, following the main example
var cookieSession = require("cookie-session");
...
app.use(cookieSession({
"name" : "sid",
"keys" : [ "bla" ]
}));
Debugging the response, we found out that no cookie was set.
It seems that the default value is actually true
, but in the README it says false
.
I saw that for express-session you could put a "wildcard" for subdomains like so:
app.use(cookieSession({
name: 'lectal-cookie',
secret: 'Bartholomew-the-Apostle',
domain: '.herokuapp.com' // << with express-session you can do this
}));
is this possible with cookie-session?
How can we make the cookie available for any subdomain of herokuapp.com? Or perhaps more securely for just two or three subdomains of herokuapp.com?
thanks :)
Hi!
I need to use sessions for my web app, but I don't understand how to use cookie-session
between my app.js
(express JS server), routes/index.js
and routes/session.js
files.
Used to navigate throw the web app.
var express = require('express');
var router = express.Router();
var printSession = require('../web_modules/printSession');
//- GET home page.
router.get('/', function(req, res, next) {
req.session.lastPage = '/home';
res.render('home');
printSession(req.session);
});
router.get('/exit', function(req, res, next) {
delete req.session.lastPage;
req.session.reset();
res.render('home');
});
module.exports = router;
Used to access to some session variables from the client in javascript. It's a REST API.
var express = require('express');
var router = express.Router();
var printSession = require('../web_modules/printSession');
router.get('/:var?', function(req, res, next) {
if(req.params[0]){
var variable = req.params[0];
res.status(200);
res.send(req.session[variable ]);
console.log(req.session[variable ]);
printSession(req.session);
}else{
res.status(200);
res.send(req.session);
printSession(req.session);
}
});
module.exports = router;
var express = require('express');
var routes = require('./routes');
var session = require('./routes/session');
[...]
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
[...]
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'public/views'));
app.set('view engine', 'ejs');
app.use(favicon(__dirname + '/public/favicon.png'));
app.use(logger('dev'));
app.use(methodOverride());
app.use(cookieSession ({
cookieName: 'session'
, secret: randomstring.generate()
, httpOnly: true
, ephemeral: true
, duration: 30 * 60 * 1000
, activeDuration: 5 * 60 * 1000
// , secure: true
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/session', session);
I would like to use the same session between routes/index.js
and routes/session.js
in order to use and modify data in it.
But after some tests, variable can be added to the session in routes/index.js
but can't be added from routes/session.js
: When a variable is added from routes/session.js
, it is not existant in routes/index.js
.
Thanks for your help!
Regards.
Currently if the cookie exceeds 4000 bytes it will fail to store in most modern browsers. This results in the user either repeatedly sending an older smaller session object, or having no session at all.
Cookie size limits are determined by the user-agent, so this should probably just be a console warning, not a failure or exception.
The field dependencies
repeats in package.json
"dependencies": {
"cookies": "~0.4.0"
},
"devDependencies": {
"connect": "*",
"mocha": "*",
"should": "*",
"supertest": "*"
},
"license": "MIT",
"dependencies": {
"debug": "*"
},
Let's fix it!
index.js#L129 prevents keys that start with _
from appearing in the output. This behaviour seems to be un-documented and surprising. It currently breaks lusca (see krakenjs/lusca#29).
I'm not too sure why, but cookie-session
doesn't work if used after connect-livereload
. Let me show you what I mean with a simple example.
This works:
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('cookie-session');
app.use(cookieParser());
app.use(session({keys: ['mysecret']}));
This instead doesn't work (session values can't be set):
var express = require('express');
var app = express();
var livereload = require('connect-livereload');
var cookieParser = require('cookie-parser');
var session = require('cookie-session');
app.use(livereload());
app.use(cookieParser());
app.use(session({keys: ['mysecret']}));
Any hint where the problem might be?
Thanks!
Hello.
When I get cookie-session from registry i don't get the latest version.
See: http://registry.npmjs.org/cookie-session/-/cookie-session-1.0.1.tgz
options.name not working.
I found the old code...
// key
var key = opts.key || 'express:sess';
Does anyone know how to fix the problem.
I can get the source code directly from github but...
Thank you.
It's been like 8 months now since -alpha was released... Should the alpha flag be removed and it published as stable?
Chrome's default request for favicon.ico causes the counter to increment by 2.
I was reading about the difference between using a Session and a Cookie Session and it seems cookie sessions are only recommended if you want to have a small session data in it.
The session middleware implements generic session functionality with in-memory storage by default. It allows you to specify other storage formats, though.
The cookieSession middleware, on the other hand, implements cookie-backed storage (that is, the entire session is serialized to the cookie, rather than just a session key. It should really only be used when session data is going to stay relatively small.
I'm looking for a solution to implement sessions in the server side of a Windows machine and it seems express-session
is not ideal for it as its not ready to work on production with the default storage module, and other modules like Redis won't be supported in Windows. Plus I'm just looking for a simple local solution.
So I was just wondering what's the recommended data limit for which cookie-session should be used.
Hello, sorry for my bad eng. I have a trouble with maxAge property, that work only from direct input, but not from config.
Example:
app.use(cookieSession({
name: 'sessiondata',
keys: ['key1', 'key2'],
cookie: {
maxAge: 1 // set the default value
}
})
);
app.get('/login', function(req, res, next) {
res.cookie('id', 'lol'); //default maxage=1 dont work
res.cookie('id2', '2222222', { maxAge: 1222});//its work
res.send(req.cookies.id+req.cookies.id2); //id = lol id2=undifened (if wait a few seconds and update page)
});
Signing is nice, but a better thing might be to just encrypt the cookies outright. This serves the purpose of signing and also hiding the session details from user inspection.
Currently Travis isn't tracking this repo (I think?)
In example: Simple view counter example
There a statement req.session.views = n++
, since we set req.session.views
with n++
, the req.session.views
will always be the old value of n
, and we'll get 1 views
in every request.
we should change the statement to
n++
req.session.views = n
I tried to test the count example of this module and noticed that it is increasing by two.
I am testing on my local machine no nginx.
It's almost as if my client machine is making a request twice behind the scenes.
What might be the issue?
EDIT: This is a copy of the http header that is sent to the client. Interesting that there are two Set-Cookie
HTTP/1.1 200 OK
Connection: keep-alive
Date: Tue, 14 Apr 2015 20:54:02 GMT
Set-Cookie: finda-sess=eyJjb3VudCI6MzN9; path=/; httponly
Set-Cookie: finda-sess.sig=g9IWmpQ9GvzHHQnDyTeOfAhauto; path=/; httponly
Transfer-Encoding: chunked
X-Powered-By: Express
"key" is too easily confused with "keys".
We can still set it from options.key
if it exists as fallback.
It seems to me that expressSession sessions get lost if the server restarts, but cookieSession sessions remain even if the server restarts. Is that correct and if so why is that? thanks
@jonathanong -- or just push the latest version, doesn't matter to me.
Hi
I was using this module implicitely via express 3.0.
I'm now trying to migrate and the only problem Iingering is with this module.
In the past I was calling something like:
app.use(express.cookieSession({
key:'sid', secret:'dog'
}));
Which became:
app.use(require('cookie-session')({
name:'sid', secret:'dog'
}));
The cookie value had a recoverable JSON fragment, which may or may not be correct to use (you tell me). The point is I was using the decoding the JSON in the client and I could have the user data without a specific request.
Old example:
s%3Aj%3A%7B%22passport%22%3A%7B%22user%22%3A22aflesler%40gmail.com%22%7D%7D.TE0pjy88BSqQLh5835U4C3ytwJmkuhUmpSkGf7e1s5o
The cookie value is a different string, seems to have went through base64:
eyJwYXNzcG9ydCI6eyJ1c2VyIjoiYXJpZWxAYW1iZXJhZHMuY29tIn19
My question is: is this due to a recent change in the encoding logic or is because I'm using the settings wrong? is there a way to extract the JSON out of this new cookie value?
Thanks!
come on
Hello,
When running the following app.js:
var cookieSession = require('cookie-session')
var helmet = require('helmet');
var express = require('express')
var app = express()
app.use(helmet());
var oneYearInSeconds = 31536000;
app.use(helmet.hsts({
maxAge: oneYearInSeconds,
includeSubDomains: true,
force: true
}));
var expiryDate = Date.now() + 60 * 60 * 1000;
app.use(cookieSession({
name: 'session',
secret: '10dfaf09-cf6f-43a9-b40b-4eaacbcceb8a',
maxAge: expiryDate,
secure : true
// secureProxy: true, // Deprecated when using 2.0.0-alpha. Says to use secure option but that stops passing on cookies. When set to true, the cookie is set to Secure. If commented out, cookie not set to Secure
}))
app.get('/', function (req, res, next) {
// Update something in the session, needed for a cookie to appear
req.session.views = (req.session.views || 0) + 1
// Write response
res.end(req.session.views + ' views')
})
app.listen(3000)
When I now curl it:
vagrant$ curl -c - -v http://localhost:3000/
Connected to localhost (127.0.0.1) port 3000 (#0)
GET / HTTP/1.1
User-Agent: curl/7.37.1
Host: localhost:3000
Accept: /
< HTTP/1.1 200 OK
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< X-Download-Options: noopen
< X-XSS-Protection: 1; mode=block
< Surrogate-Control: no-store
< Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
< Pragma: no-cache
< Expires: 0
< Strict-Transport-Security: max-age=31536; includeSubDomains
< Date: Tue, 13 Dec 2016 11:27:37 GMT
< Connection: keep-alive
< Content-Length: 7
<
Connection #0 to host localhost left intact
You see no cookies are added nor set. When I comment out secure:true and set secureProxy : true, then a cookie is returned, you'll see something like:
#HttpOnly_localhost FALSE / TRUE 2961374488 session eyJ2aWV3cyI6MX0=
#HttpOnly_localhost FALSE / TRUE 2961374488 session.sig DJaPtrG-tmTnVr33fOWXqWGnVlw
See also my comment at the end of the secureProxy field.
Versions used:
node js: 6.7.0
express: 4.13.30
cookie-session: 1.2.0
helmet: 0.14.0
Am I doing something wrong? Or maybe it's helmet being in the way in some form? Update: nope, when commenting out the helmet parts, same behavior.
Where is this stored?
In memory in the node js server / the browser.
I didnt see it in the browser so i presume it is in memory.
The following happens in express 4:
req.flash('error', error.toString());
assert(req.session.isChanged == false)
req.session.foo = req.session.flash;
assert(req.session.isChanged == true)
But even doing that doesn't persist the data, both foo
and flash
get serialized as empty arrays. But if I set foo
manually to an array or object then that does work.
I'm using node with IIS by using iisnode and I'm having troubles setting the CookieSession option secure:true
.
I'm using HTTPS on IIS and I'm redirecting any HTTP to HTTPS.
But evenw ith this, if I set the CookieSession option secure:true
, the session won't have any content after login.
secure: a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS).
I'm forced to use secure:false
to make it work. Why is it?
Hi. I'm trying to save cookies by path like this:
app.use(session({
name: 'test.connect.sid',
keys: ['key1', 'key2'],
cookie: {
secure: false,
domain: 'localhost',
path: '/test',
expires: expiryDate
}
}));
But when I look on cookies in browser I see the following:
Path is default, '/', expire date is default too.
The default cookie name express:sess
contains :
, which is not a valid token character in accordance with RFC6265 and RFC2616. Although most web browsers and servers allow this, it causes problems in some more strict environment such as spray.
Would you consider remaining it? If so, should we take backward compatibility into account?
p.s. I posted the same issue as koajs/session#28.
How are we suppose to renew the session?
Using req.sessionOptions.maxAge = req.session.maxAge
within a middle-ware?
It looks like 2.x still isn't published. I really want that change to include underscore prefixed properties.
The documentation doesn't seem to be very clear to me.
It says
Other options are passed to cookies.get() and cookies.set()
cookies
there?set
to set the options we want?I was trying to use cookieSession as express-session, but it seems that's not the way it works:
var cookieSession = require('cookie-session');
app.use(cookieSession({
maxAge: 20*60*1000, //20 mins
httpOnly: true,
secure: true,
secureProxy: true,
keys: ['key1', 'key2']
}));
Add to README how to install cookie-session module
After reading the documentation I don't have it very clear what is the keys
parameter for in the cookie-session configuration.
I'm not an expert on cookies and the description doesn't help me much on that regard.
keys
The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.
But it seems to be a compulsory field, if I don't add it I get an error:
C:\inetpub\wwwroot\app\node_modules\cookie-session\index.js:55
if (!keys && opts.signed) throw new Error('.keys required.');
So I ended up using keys: ['key1', 'key2']
as in the examples, but I have no idea why.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.