Node Express setting cookies - node.js

I may be misunderstanding here.
I have a node server running at localhost:3000, and a React app running at localhost:8080.
The React app is making a get request to the node server - my server code for this looks like:
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(cookieParser());
app.get('/', function (req, res) {
let user_token = req.cookies['house_user']; // always empty
if (user_token) {
// if the token exists, great!
} else {
crypto.randomBytes(24, function(err, buffer) {
let token = buffer.toString('hex');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
res.cookie('house_user', token, {maxAge: 9000000000, httpOnly: true, secure: false });
res.send(token);
});
}
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
I'm trying to set the house_user token, so that I can later keep track of requests from users.
However, the token is not being set on the user (request from localhost:8080) - the house_user token is always empty (in fact, req.cookies is entirely empty). Do I need to do something else?

I just tried the code below (and it worked). As a reminder, you can just paste this in myNodeTest.js, then run node myNodeTest.js and visit http://localhost:3003. If it does work, then it probably means you're having CORS issues.
[EDIT] withCredentials:true should do the trick with axios.
axios.get('localhost:3000', {withCredentials: true}).then(function (res) { console.log(res) })
const express = require('express')
const cookieParser = require('cookie-parser')
const crypto = require('crypto');
const port = 3003
app.use(cookieParser());
app.get('/', function (req, res) {
let user_token = req.cookies['house_user']; // always empty
if (user_token) {
// if the token exists, great!
} else {
crypto.randomBytes(24, function(err, buffer) {
let token = buffer.toString('hex');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
res.cookie('house_user', token, {maxAge: 9000000000, httpOnly: true, secure: true });
res.append('Set-Cookie', 'house_user=' + token + ';');
res.send(token);
});
}
});
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})

Making my comment into an answer since it seemed to have solved your problem.
Since you are running on http, not https, you need to remove the secure: true from the cookie as that will make the cookie only be sent over an https connection which will keep the browser from sending it back to you over your http connection.
Also, remove the res.append(...) as res.cookie() is all that is needed.

Related

Nodejs server doesn't recognize saved cookie sessionId

I have a nodejs/express server with the following code
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cookieparser = require("cookie-parser");
const { randomBytes } = require('crypto');
const COOKIE_SECRET = 'aavslrhe158ewuycvasjy7et2hvh2ytt0';
var SESSIONS = {};
app.use(
express.static(__dirname + '/public'),
bodyParser.urlencoded({ extended: false }),
bodyParser.json(),
cookieparser(COOKIE_SECRET)
);
app.get("/login", function (request, response){
response.sendFile(__dirname + "/views/login.html");
});
app.post("/verifyaccount", function (request, response){
const nextSessionId = randomBytes(16).toString('base64');
response.cookie("sessionId", nextSessionId, { maxAge: 3600, httpOnly: true, Secure: true });
SESSIONS[nextSessionId] = request.body.sz_Username;
response.status(response_status).redirect('/admin');
}
app.get("/admin", function (request, response){
if(!is_authorized(request.cookies.sessionId)){
response.redirect('/login');
}
else{
response.sendFile(__dirname + "/views/admin.html");
}
});
app.post("/addproject", function(request, response){
if(!is_authorized(request.cookies.sessionId)){
response.redirect('/login');
}
else{
}
}
function is_authorized(sessionId){
var authorized = false;
if (SESSIONS[sessionId]) {
authorized = true;
}
return authorized;
}
So when I login the credentials go to /verifyaccount, there I check if they're correct. Then it creates a cookie in my browser: sessionId:"KlS6xuspQ4GczVqqpSc2Nw%3D%3D" and stores it in the SESSIONS variable. I get redirect to /admin where the authorization works.
But when I am in admin.html and send data to /addproject I get redirect to /login because the authorization fails. The request.cookies.sessionId is undefined. The cookie keeps existing in my browser, so I don't know what the problem is, since the cookie was correct in /admin.
Edit: after being redirect to /admin from /login if I go back to /login or / and then attempt to /admin from the url I get the same undefined error. Which should not occur since the cookie expires in 1 hour.
"maxAge is in milliseconds. Your cookie is expiring 3.6 seconds after you set it"
-clubby789 htb

Why is cookie not getting sent to server

I have a nodejs express application hosted on a server. Basically, I have two endpoints:
POST /session - this is where I send back the cookie
GET /resource - this is where I check if the cookie is sent back, if not I send back 401 not found, like so
On the frontend, which is on a different domain (let's say a newly generated angular-cli application which is running on htpp://localhost:4200), I try to call the /session API, which returns the cookie header, but a consecutive /resource API call will not send the cookie back to the server. What am I doing wrong?
Serve code is as follows:
// server.js
const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");
const cors = require("cors");
app.use(cors());
app.use((req, res, next) => {
console.log(req.method, req.url, JSON.stringify(req.headers, null, 2));
next();
});
app.use(cookieParser());
app.get("/", (req, res) => {
res.send({ status: "running" });
});
app.post("/session", (req, res) => {
const cookie = `AuthSession=token; Path=/;`;
res.setHeader("Set-Cookie", cookie);
res.send({ status: "logged in" });
});
app.get("/resource", (req, res) => {
const authSessionCookie = req.cookies && req.cookies["AuthSession"];
if (!authSessionCookie) {
res.sendStatus(401);
return;
}
res.send({ resource: "resource" });
});
const listener = app.listen(process.env.PORT, () => {
console.log("Your app is listening on port " + listener.address().port);
});
This is the cookie sent back by the /session API:
Angular code as follows:
export class AppComponent {
constructor(private readonly httpClient: HttpClient) {
this.httpClient
.post("https://uneven-glowing-scorpion.glitch.me/session", {})
.subscribe(resp => {
console.log(resp);
this.httpClient
.get("https://uneven-glowing-scorpion.glitch.me/resource")
.subscribe(resp => {
console.log(resp);
});
});
}
}
As you can see the server is available at https://uneven-glowing-scorpion.glitch.me for testing purposes.
http://localhost:4200 and https://uneven-glowing-scorpion.glitch.me are not the same domain, therefore no cookie gets sent. It's really just that simple. There is no way around that with cookies. Cookies cannot cross domains. That's what makes them secure.
The reason your HTTP call works with Postman is because that application is very forgiving in these situations; browsers are not. There are many questions about this on SO.

Reading Cookies from Express Middleware

I'm making an app using the Express and Unblocker modules, along with CookieParser for cookie reading. I have a simple system where an if statement read req.cookies.visits and sees if it is 0 or undefined, then redirects to a password screen. However, a problem arises when the Unblocker module is taken into account. Doing
app.get('/proxy', function(req, res){
if(req.cookies.visits==0||req.cookies.visits==undefined){
res.redirect("/password");
} else {
res.sendFile(__dirname + '/public/index.html');
}
});
doesn't read the cookie for when the request is made (because the route is /proxy/http address). I've tried using express middleware, but doing req.cookie.visits results in an undefined error. Unblocker also has a built in middleware functionality, but the page on npm only shows how to do a response and not a request.
Basically, how could I read a cookie with every request and be compatible with this module?
Check out a full example with middleware :
const express = require('express')
const app = express();
const port = 3000;
var Unblocker = require('unblocker');
const cookieParser = require("cookie-parser");
app.use(cookieParser());
app.use(new Unblocker({prefix: '/proxy/'}));
function checkVisits(req,res,next){
let visits;
try {
visits = req.cookies.visits;
if(isNaN(visits)){
visits = 0;
}
console.log("visits:" + visits);
} catch {
console.log("no visits");
visits = 0;
}finally{
if(visits === 0){
res.redirect("/password");
return;
}
res.visits = parseInt(visits)+1;
res.cookie('visits',res.visits, { maxAge: 900000, httpOnly: true });
return next();
}
}
//add checkVisits(req,res,next) as a middleware
app.get('/index',checkVisits, function (req, res) {
res.send('index visits:'+res.visits);
})
//add checkVisits(req,res,next) as a middleware
app.get('/home',checkVisits, function (req, res) {
res.send('home visits:'+res.visits);
})
app.get('/password', function (req, res) {
res.send('password page');
})
app.listen(port, () => console.log("App listening on port %s!", port))
The checkVisits(req,res,next) middleware will check for visits cookie. If visits cookies is 0 the user will redirected to route /password .

React intercepts /auth/twitter/when HTTPS. I want to access /auth/twitter/ from my node server not the react application

New to React/Node.
I have an implementation of React(React-boiler-plate with webpack etc)/Node running on the same host on Heroku.
I am using passport and twitter-oath sessions.
When I hit the endpoint http://example.heroku.com/auth/twitter/callback everything works accordingly (as well as running local dev server).
When I try to access it via HTTPS https://example.heroku.com/auth/twitter/callback React intercepts it and shows a page not found page.
I am trying to get an understanding to understand why this happens and the best way to handle this in a "production" like environment. I would like to be handle /auth/twitter and /auth/twitter/callback all on the same host.
I have tried adding http proxy in misc places as well as package.json and to no avail I am spinning my wheels.
Thank you in advance.
auth routes
module.exports = app => {
app.get('/api/logout', (req, res) => {
// Takes the cookie that contains the user ID and kills it - thats it
req.logout();
// res.redirect('/');
res.send(false);
// res.send({ response: 'logged out' });
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get(
'/auth/twitter/callback',
passport.authenticate('twitter', {
failureRedirect: '/'
}),
(req, res) => {
res.redirect('/dashboard');
}
);
app.get('/api/current_user', (req, res) => {
// res.send(req.session);
// res.send({ response: req.user });
res.send(req.user);
});
};
index.js
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(
//
cookieSession({
// Before automatically expired - 30 days in MS
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.COOKIE_KEY]
})
);
app.use(passport.initialize());
app.use(passport.session());
require('./routes/authRoutes')(app);
// They export a function - they turn into a function - then immediately call with express app object
app.use('/api/test', (req, res) => {
res.json({ test: 'test' });
});
setup(app, {
outputPath: resolve(process.cwd(), 'build'),
publicPath: '/',
});
// get the intended host and port number, use localhost and port 3000 if not provided
const customHost = argv.host || process.env.HOST;
const host = customHost || null; // Let http.Server use its default IPv6/4 host
const prettyHost = customHost || 'localhost';
/ Start your app.
app.listen(port, host, async err => {
if (err) {
return logger.error(err.message);
}
// Connect to ngrok in dev mode
if (ngrok) {
let url;
try {
url = await ngrok.connect(port);
} catch (e) {
return logger.error(e);
}
logger.appStarted(port, prettyHost, url);
} else {
logger.appStarted(port, prettyHost);
}
});
console.log('Server listening on:', port);
/**
* Front-end middleware
*/
module.exports = (app, options) => {
const isProd = process.env.NODE_ENV === 'production';
if (isProd) {
const addProdMiddlewares = require('./addProdMiddlewares');
addProdMiddlewares(app, options);
} else {
const webpackConfig = require('../../internals/webpack/webpack.dev.babel');
const addDevMiddlewares = require('./addDevMiddlewares');
addDevMiddlewares(app, webpackConfig);
}
return app;
};
const path = require('path');
const express = require('express');
const compression = require('compression');
module.exports = function addProdMiddlewares(app, options) {
// messing around here
const proxy = require('http-proxy-middleware');
const apiProxy = proxy('/api', { target: 'http://localhost:3000' });
const apiProxy2 = proxy('/auth', { target: 'http://localhost:3000' });
app.use('/api', apiProxy);
app.use('/auth/*', apiProxy2);
const publicPath = options.publicPath || '/';
const outputPath = options.outputPath || path.resolve(process.cwd(), 'build');
// compression middleware compresses your server responses which makes them
// smaller (applies also to assets). You can read more about that technique
// and other good practices on official Express.js docs http://mxs.is/googmy
app.use(compression());
app.use(publicPath, express.static(outputPath));
app.get('*', (req, res) =>
res.sendFile(path.resolve(outputPath, 'index.html')),
);
};
const path = require('path');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
function createWebpackMiddleware(compiler, publicPath) {
return webpackDevMiddleware(compiler, {
logLevel: 'warn',
publicPath,
silent: true,
stats: 'errors-only',
});
}
module.exports = function addDevMiddlewares(app, webpackConfig) {
const compiler = webpack(webpackConfig);
const middleware = createWebpackMiddleware(
compiler,
webpackConfig.output.publicPath,
);
app.use(middleware);
app.use(webpackHotMiddleware(compiler));
// Since webpackDevMiddleware uses memory-fs internally to store build
// artifacts, we use it instead
const fs = middleware.fileSystem;
app.get('*', (req, res) => {
fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
if (err) {
res.sendStatus(404);
} else {
res.send(file.toString());
}
});
});
};
Chances are you have a service worker that is running client side and intercepting the requests, then serving your react app from it's cache.
One hint that gives it away is that the service worker will only be installed / run over https https://developers.google.com/web/fundamentals/primers/service-workers/#you_need_https
Solution would be to either edit the service worker code to have it not serve for the auth urls or disable it all together if you are not planning to build an app around it, it may be more trouble than it is worth.

ExpressJS & Websocket & session sharing

I'm trying to make a chat application based on Node.js. I'd like to force websocket server (ws library) to using ExpressJS session system. Unfortunately, I've got stuck. MemoryStore hashes used to get sessions' data are different than session IDs in cookies. Could somebody explain me what I'm doing wrong?
Websocket server code part:
module.exports = function(server, clients, express, store) {
server.on('connection', function(websocket) {
var username;
function broadcast(msg, from) {...}
function handleMessage(msg) {...}
express.cookieParser()(websocket.upgradeReq, null, function(err) {
var sessionID = websocket.upgradeReq.cookies['sid'];
//I see same value in Firebug
console.log(sessionID);
//Shows all hashes in store
//They're shorter than sessionID! Why?
for(var i in store.sessions)
console.log(i);
store.get(sessionID, function(err, session) {
websocket.on('message', handleMessage);
//other code - won't be executed until sessionID in store
websocket.on('close', function() {...});
});
});
});
}
store object definition:
var store = new express.session.MemoryStore({
reapInterval: 60000 * 10
});
app configuration:
app.configure(function() {
app.use(express.static(app.get("staticPath")));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store: store,
secret: "dO_ob",
key: "sid"
}));
});
Part of main code:
var app = express();
var httpServer = http.createServer(app);
var websocketServer = new websocket.Server({server: httpServer});
httpServer.listen(80);
Sample debugging output:
- websocket.upgradeReq.headers.cookie "sid=s%3A64a%2F6DZ4Mab8H5Q9MTKujmcw.U8PJJIR%2BOgONY57mZ1KtSPx6XSfcn%2FQPZ%2FfkGwELkmM"
- websocket.upgradeReq.cookies["sid"] "s:64a/6DZ4Mab8H5Q9MTKujmcw.U8PJJIR+OgONY57mZ1KtSPx6XSfcn/QPZ/fkGwELkmM"
- i "64a/6DZ4Mab8H5Q9MTKujmcw"
I found this works for me. Not sure it's the best way to do this though. First, initialize your express application:
// whatever your express app is using here...
var session = require("express-session");
var sessionParser = session({
store: session_store,
cookie: {secure: true, maxAge: null, httpOnly: true}
});
app.use(sessionParser);
Now, explicitly call the session middleware from the WS connection. If you're using the express-session module, the middleware will parse the cookies by itself. Otherwise, you might need to send it through your cookie-parsing middleware first.
If you're using the websocket module:
ws.on("request", function(req){
sessionParser(req.httpRequest, {}, function(){
console.log(req.httpRequest.session);
// do stuff with the session here
});
});
If you're using the ws module:
ws.on("connection", function(req){
sessionParser(req.upgradeReq, {}, function(){
console.log(req.upgradeReq.session);
// do stuff with the session here
});
});
For your convenience, here is a fully working example, using express, express-session, and ws:
var app = require('express')();
var server = require("http").createServer(app);
var sessionParser = require('express-session')({
secret:"secret",
resave: true,
saveUninitialized: true
});
app.use(sessionParser);
app.get("*", function(req, res, next) {
req.session.working = "yes!";
res.send("<script>var ws = new WebSocket('ws://localhost:3000');</script>");
});
var ws = new require("ws").Server({server: server});
ws.on("connection", function connection(req) {
sessionParser(req.upgradeReq, {}, function(){
console.log("New websocket connection:");
var sess = req.upgradeReq.session;
console.log("working = " + sess.working);
});
});
server.listen(3000);
I was able to get this working. I think you need to specify the secret on cookieParser instead of session store.
Example from my app:
var app = express();
var RedisStore = require('connect-redis')(express);
var sessionStore = new RedisStore();
var cookieParser = express.cookieParser('some secret');
app.use(cookieParser);
app.use(express.session({store: sessionStore}));
wss.on('connection', function(rawSocket) {
cookieParser(rawSocket.upgradeReq, null, function(err) {
var sessionID = rawSocket.upgradeReq.signedCookies['connect.sid'];
sessionStore.get(sessionID, function(err, sess) {
console.log(sess);
});
});
});
Feb 2022 update:
verifyClient is now discouraged. New methods of doing this is described in an issue comment.
Consult the example code for session parsing and verification for a full usage example. Sample of the verification function:
server.on('upgrade', function (request, socket, head) {
console.log('Parsing session from request...');
sessionParser(request, {}, () => {
if (!request.session.userId) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
console.log('Session is parsed!');
wss.handleUpgrade(request, socket, head, function (ws) {
wss.emit('connection', ws, request);
});
});
});
Original answer:
In version 3.2.0 of ws you have to do it a bit differently.
There is a full working example of express session parsing in the ws repo, specifically using a new feature verifyClient.
A very brief usage summary:
const sessionParser = session({
saveUninitialized: false,
secret: '$eCuRiTy',
resave: false
})
const server = http.createServer(app)
const wss = new WebSocket.Server({
verifyClient: (info, done) => {
console.log('Parsing session from request...')
sessionParser(info.req, {}, () => {
console.log('Session is parsed!')
done(info.req.session.userId)
})
},
server
})
wss.on('connection', (ws, req) => {
ws.on('message', (message) => {
console.log(`WS message ${message} from user ${req.session.userId}`)
})
})
WS v3.0.0 and above, has changed the behaviour so the given answers won't work out of the box for those versions. For current versions, the signature of the connection method is [function(socket, request)] and the socket no longer contains a reference to the request.
ws.on(
'connection',
function (socket, req)
{
sessionParser(
req,
{},
function()
{
console.log(req.session);
}
);
}
);
Currently, below is my workaround which is working fine. I just don't know it's disadvantages and security. I just prevent the server from listening if it doesn't have a session. (Share session from express-session to ws)
I haven't fully tested this though.
var http = require('http');
var express = require('express');
var expressSession = require('express-session');
var router = express.Router();
var app = express();
const server = http.createServer(app);
router.get('/', function(req, res, next) {
if(req.session.user_id) {
// Socket authenticated
server.listen(8080, function listening(){});
}
});

Resources