I use lusca to handle csrf attacks for my application. in my express application, when I process the html page and pass the _csrf token to it for placement on the hidden input, everything is correct, because lusca checks the html _csrf token and finds a match.
my controller:
response.render("root/home", { _csrf: response.locals._csrf });
my html page:
<input type="hidden" name="_csrf" value="{{_csrf}}" />
But when I want to export the json response for the POST request , I cannot send the _csrf token, so lusca cannot find a match (I think the problem is here) and give me this error:
Error: CSRF Token Mismatch
my controller:
response.json({ status: "success" });
UPDATE:
The csrf secret (not a token, note) is regenerated or deleted for some time between the initial GET and POST . The only way this is possible is that the value stored as _csrfSecret in the session is changed or deleted between requests. Verify that the session is working correctly. FROM THIS SOURCE
but still I can not find a solution!
UPDATE 2:
We have 2 strategies for generating csrf tokens ... per session and per request . in my application tokens are generated by request. the problem is when I ask for the first time a new token and a secret will be generated. this means that the new token and secret match. but when I save the token and send it using an ajax request (in the header or body); this ajax request will force the old secret to expire and create a new one. therefore my token does not match it.
source share