1

I get "ForbiddenError: invalid csrf token" when I try to run my register test. I do get an token from my function but i think i implementing it wrong. Maybe I have to set it in the header somehow?

my test file

var request = require('supertest');
var server = request.agent(config.TEST_URL);

// function to get the csrf token from the client
function extractCsrfToken (res) {
    var $ = cheerio.load(res.text);
    return $('[name=_csrf]').val();
}

describe('POST /register', function () {

    var csrfToken;

    beforeEach(function (done) {
        server.get('/register')
            .end(function (err, res) {
                if (err) return done(err);
                csrfToken = extractCsrfToken(res); // fetch the csrf token from client
                done();
            });
    });

    it('should accept the result', function (done, res) {
        server
            .post('/register')
            .send({
                _csrf: csrfToken,
                username: 'testing',
                email:'mjo@test.com',
                password:'password' })
            .expect(201)
            .end(done);
    });

});

Here is some part of my app.js with session information

var sessions = require('client-sessions');

app.use(sessions({
    cookieName: 'session',
    secret: 'random secret string',
}));

app.use(csrf());

Thanks.

roYal
  • 197
  • 1
  • 2
  • 16
  • I have almost exactly the same setup as you do, client-sessions + csurf but the solution posted didn't help me out. Can you please let me what was the extra step you did to fix this? – larrydalmeida Jan 18 '17 at 10:57
  • Never mind, I forgot to send the send session cookies with my POST `.set('cookie', res.headers['set-cookie'])`. Works now. – larrydalmeida Jan 18 '17 at 11:02

0 Answers0