How to get a csrfToken from an /api req object?
-
Hi, I had been rendering a form using a plain old express rendered route and I could get a valid csrfToken from req.csrfToken() in the render method. However, I'm switching the form over to work as part of a normal nodebb page and now req.csrfToken() is undefined. I've searched around, but haven't found an example of where to properly get a csrf token to send as part of a /api request.
Any thoughts?
-
@julian said:
You should be able to retrieve a CSRF token thusly:
require(['csrf'], function(csrf) { var token = csrf.get(); });
You can create the hidden input via js, or update it via js, or send it as a header (called
x-csrf-token
).I'm only vaguely familiar with the concept of csrf, how does this work exactly?
Does the destination route not need Middleware.applyCSRF applied to it to work? Therefore, it would only work with custom routes?
-
@julian Thanks this did the trick!
I used it like this in my client side code:
<input id="csrfToken" type="hidden" name="_csrf" value="" /> ... $(window).on('action:ajaxify.end', function(data) { require(['csrf'], function(csrf) { var csrfToken = csrf.get(); console.log('obtained csrfToken: ' + csrfToken); $('#csrfToken').val(csrfToken); }); });
@yariplus I'm not really sure about your specific question. I have a feeling that the csrf tokens are generated based on a csrfSecret that is stored in the user's session. You could check that the session has this loaded on the server side with this:
var util = require('util'); console.log('user session' + util.inspect(req));
For me, this results in:
user session: { cookie:
{ path: '/',
_expires: Sun Nov 22 2015 09:52:23 GMT-0800 (PST),
originalMaxAge: 1209599988,
httpOnly: true },
csrfSecret: '70lFS_InV_56D1gvV9TDKgJX',
flash: {},
passport: { user: 1 } }