I have a problem in Express 4.x.I can't set any cookies. I want to set a cookie via Ajax request, i do the request, my server-side res.cookie() is executed, in my response headers i can find my 'set-cookie' header with the specific name and value, but nothing happens, the cookie is not registered. I have no HttpOnly or secure flag.
Cookie set example :
res.cookie('my_cookie','value',{maxAge:500,secure:false,httpOnly:false});
What i've noticed is that if i set maxAge 500 for example, my cookie expiration date from response headers is about 5 hours ago, so i tried to add a bigger value, but nothing happened.
It is like my set-cookie header is ignored. I don't use AngularJS, just jQuery.
If i put the set-cookie content in document.cookie from js console, the cookie is registered..
Thanks in advance and sorry for my bad english .
Version 4.0 removed a lot of the convenience middleware from the library for a more modular architecture; in this case you need to reference the cookie-parser middleware. Without it req.cookies is just an empty {}.
$npm install cookie-parser
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
You also need it to sign cookies:
Related
I am using csurf as recommended in my Express application to guard against cross sites forgeries. I have registered it globally(illustrated with code below) and so far so good.
Now, I have added multer.js to be able to upload images and as their documentation recommends it, it's more secure to attach multer to each express route where you intend to use.
Now when I do attach multer to my upload routes, I am faced with a 'ForbiddenError: invalid csrf token' and I really don't know why, as my view I am submitting the form from, as a csrf token attached to it.
Below is my code and I would really appreciated any help/suggestions. Thank you all
app.js
const express = require('express');
const csrf = require('csurf');
const csrfProtection = csrf();
const shopRoute = require('../Routes/shop');
const app = express();
app.use(csrfProtection);
app.use(shopRoutes);
routes.js
const express = require('express')
const router = express.Router();
const multer = require('multer');
const controllers = require('../Controllers/shop');
router.post('/upload', multer({storage: multer.memoryStorage(), fileFilter: fileFilter), controller.uploadFunction);
I'm guessing the problem is that when you are uploading a file, the content type of the request becomes multipart/form-data, and you cannot simply pass the csrf token to Express in the body anymore.
The API allows to pass it in the URL though. Try passing the token in the _csrf parameter, that I think should solve your issue. So simply post the form to .../?_csrf={your_token}. Note though that this is slightly less secure than passing your csrf token in the request body, and might be flagged as a potential vulnerability in later penetration tests if you ever have one.
Alternatively, for a little more security, you can also pass it as a request header, but that might be a little trickier on the client side. According to the docs, Express will take the token from the following:
req.body._csrf - typically generated by the body-parser module.
req.query._csrf - a built-in from Express.js to read from the URL query string.
req.headers['csrf-token'] - the CSRF-Token HTTP request header.
req.headers['xsrf-token'] - the XSRF-Token HTTP request header.
req.headers['x-csrf-token'] - the X-CSRF-Token HTTP request header.
req.headers['x-xsrf-token'] - the X-XSRF-Token HTTP request header.
So adding a csrf-token header should also work.
Disclaimer: I don't know multer.js at all, and have very little experience with Express.
It seems that express 4 has unbundled cookieparser, so I included it as it details in the docs, but res.cookie() doesn't seem to send the cookie anymore.
I have
var cookieParser = require('cookie-parser');
followed by
res.cookie("token",tokval, { maxAge: 900000, httpOnly: false });
but document.cookie returns nothing.
Express docs: http://expressjs.com/en/api.html#req.cookies
Any thoughts or suggestions (or prayers I suppose) would be much appreciated
You won't see HttpOnly cookies in the browser. They are cookies that are automatically sent by the browser but unavailable to scripts on the page.
Hi all i'm using Express 4 with cookie-parser. For some reason the cookie is being set in the res object, but is not really stored in the browser. I wanted to see ALL cookies that are about to be passed at the end (all cookies for the current response object). Any idea on how to get them?
Use this:
console.log('Cookies: ', res._headers["set-cookie"]);
Explanation: As the cookies are set in the response header as "set-cookie" attribute.
I'm checking and setting a couple of cookies in the middleware before hitting the route. After hitting the route, inside the handler, I'm trying to access the aforementioned set cookies but the response object has no accessor for these set cookies.
# similar to req.cookies.cookie_name to access cookies sent by the client
stored_value = res.cookies.cookie_name # this method doesn't exist
The response object exposes a getHeader method, using which I attached a simple cookie parser on response.getHeader('Set-Cookie') to the response object.
app.use (req, res, next) ->
#
# returns a hash of cookie_name: cookie_value,
# or cookie_value if cookie_name is sent as an argument
#
res.jit_cookies = (cookie_name) ->
cookies = {}
for cookie in this.getHeader('Set-Cookie')
tokens = cookie.split(';')[0].split('=')
cookies[tokens[0]] = tokens[1]
if cookie_name? then cookies[cookie_name] else cookies
next()
So now I can access the cookies I set anywhere I have access to the response object.
res.jit_cookies() # returns a hash of all cookies set
res.jit_cookies('lang') # returns the value of the 'lang' cookie
I'm using cookies so that the state of the response is bound to the response object which is later accessed in many places.
Is this okay to do? Are there other (and better) ways to track and access the same information that I'm trying to use cookies for?
There already is a cookie-parser middleware that parses cookies for you and puts them in req.cookies.
As far as accessing the req when you only have res, you can access res.req.
You need to use a middleware called: "cookieParser"
If you are using Express v3.X:
app.use(express.cookieParser());
instead if you are using 4.X you need to also import it and use it as follows:
var cookieParser = require('cookie-parser')
app.use(cookieParser())
Of course, for the second option you need to first install the package:
$ npm install cookie-parser
In that way you can get access of cookies like:
req.cookies // returns an object
req.cookies['yourCookieName']
Assuming one sets the cookieParser in a Node application using Express JS, does it mean that a session will always be created if none is not available in the incoming request?
self.app.use(express.bodyParser());
self.app.use(express.cookieParser());
self.app.use(express.session({...]);
In other words, does req.session will ever be null or undefined?
Yes, the session middleware will put a session object on each request given your code above. Not the cookie parser has one well-defined job: parse the cookie header from HTTP header key/value to JS object. End of story. It's the session middleware that handles creation and population of the session object.