session access for CSRF tokens
See original GitHub issueI’ve recently started using supertest to write tests for an Express app. I have added CSRF protection middleware, and I’m having trouble testing my login route. Tests work fine if I remove CSRF, but that’s obviously not ideal. This also prevents me from testing parts of the app that are behind authentication.
Based on examples in https://github.com/visionmedia/superagent/blob/master/lib/node/agent.js, I started fiddling with a solution, but I haven’t figured out how to get the csrf token, then send that token back with the next POST.
a snippet of my code:
agent1 = superagent.agent()
agent2 = superagent.agent()
token = null
loginUser = (agent) ->
(done) ->
onResponse = (err, res) ->
res.should.have.status 200
done()
agent1.get("http://localhost:3000/", (req, res) ->
token = req.session._csrf
)
agent2.post("http://localhost:3000/login").send(
# login creds..
_csrf : token
).end onResponse
req seems to be null in the first agent each time, and I’m not really sure why? Is this something I should use PhantomJS or Zombie JS for?
My apologies for my ignorance; I am stuck on this and would appreciate any input.
Issue Analytics
- State:
- Created 11 years ago
- Comments:9 (3 by maintainers)
Top GitHub Comments
I realize, in retrospect, it’s much easier simply to disable CSRF middleware in the test environment.
Then I use @NODE_ENV=test like in Express JS’s Makefile figured this might help someone else down the line
closing