3

I am using node 6.5.0 and npm 3.10.3.

I'm getting this invalid csrf token error when I am trying to log in the user to the site.

{ ForbiddenError: invalid csrf token at csrf (/Users/Documents/web-new/node_modules/csurf/index.js:113:19)

The login with storing session in redis works without the csurf module (https://github.com/expressjs/csurf). With the csurf module, the session ID is getting stored in redis but I am not able to return the proper response to the client to log in the user. I am using Angular2 with node/express. From what I understand, Angular2 by default supports CSRF/XSRF with the CookieXSRFStrategy when using HTTP service, so all I need to do is configure something on the node/express side. The Angular2 app with webpack-dev-server is running on localhost:3000 while the node/express server is running on localhost:3001. I am supporting CORS.

I am able to see cookie with name XSRF-TOKEN in devtools at localhost:3000.

Could you kindly recommend how I might fix this error?

//cors-middleware.js

var corsOptions = {
   origin: 'http://localhost:3000',
  credentials:true
}

app.use(cors(corsOptions));
app.use(function(req, res, next) {
    res.setHeader('Content-Type','application/json');
        next();
    })
};

//index.js

import path from 'path';
import session from 'express-session';
import connectRedis from 'connect-redis';
import rp from 'request-promise';
import * as _ from 'lodash';
import cors from 'cors';
import csurf from 'csurf';

const redisStore = connectRedis(session);
const dbStore = new redisStore(db);

let baseUrl = app.getValue('baseUrl');

/* ~~ api authentication ~~ */

let options = {
    method: 'POST',
    url: `${baseUrl}/authenticate`,
    rejectUnauthorized: false,
    qs: {
     username: 'someUsername', key: 'someKey'
    },
    json: true
};
rp(options)
    .then(response => {
        let apiToken = response.response;
        app.setValue("token", apiToken);
    })
    .catch(err => {
        console.error(err);
    });

/* ~~ configure session ~~ */

app.use(session({
    secret: app.getValue('env').SESSION_SECRET,
    store: dbStore,
    saveUninitialized: false,
    resave: false,
    rolling: true,
    cookie: {
        maxAge: 1000 * 60 * 30 // in milliseconds; 30 min
    }
}));

/* ~~ login user ~~ */

let csrf = csurf();

app.post('/loginUser', csrf, (req, res, next) => {
    let user = {};
    let loginOptions = {
        method: 'POST',
        url: `${baseUrl}/client/login`,
        rejectUnauthorized: false,
        qs: {
            token: app.getValue('token'),
            email: req.body.email,
            password: req.body.password
        },
        headers: {
            'Content-Type': 'application/json'
        },
        json: true
    };

    rp(loginOptions)
        .then(response => {
            let userToken = response.response.token;
            let clientId = response.response.clientId;

            req.session.key = req.session.id;

            user.userToken = userToken;
            user.clientId = clientId;


            let clientAttributeOptions = {
                url: `${baseUrl}/client/${clientId}/namevalue`,
                rejectUnauthorized: false,
                qs: {
                    token: app.getValue('token'),
                    usertoken: userToken
                },
                json: true
            };

            return rp(clientAttributeOptions);
        })
        .then(response => {
            req.session.user = user;
                res.send({user:user})
        })
        .catch(err => {
            next(err);
        })

});
Cookies
  • 325
  • 1
  • 4
  • 10

1 Answers1

1

My issue was that I was including the csrf function as a middleware only in the app.post('/loginUser) route.

When I included it for all routes, the module worked fine.
let csrf = csurf(); app.get('/*', csrf, (req, res) => { res.sendFile(app.get('indexHTMLPath')); });

Cookies
  • 325
  • 1
  • 4
  • 10