expressjs / csurf

CSRF token middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

per-page CSRF token support

francisfernando opened this issue · comments

Currently we implement the CSURF in our project to add security feature.

Here how we implement it :

under routes

/** Implement CSRF Token */
var csrfProtection = csrf();

/** Home page */
app.get('/user', isAuthenticated, csrfProtection, home.show);

app.post('/new/user', isAuthAPI, csrfProtection, user.update);

Add the token in meta data

<meta name="csrf-token" content="{{_csrftoken}}">

Then override AJAX to add the token

/** SET CSRF */
var CSRF_HEADER = 'X-CSRF-Token';

var setCSRFToken = function (securityToken) {
  jQuery.ajaxPrefilter(function (options, _, xhr) {
    if (!xhr.crossDomain && options.type != 'get') {
      xhr.setRequestHeader(CSRF_HEADER, securityToken);
    }
  });
};

setCSRFToken($('meta[name="csrf-token"]').attr('content'));
/** END SET CSRF */

Then i try the a single token in all the page and it was working. It should be valid only in one page or one request ?

The token is validated against the visitor's session or csrf cookie.

I didn't put any option on the csrf(); i guess it will be on the session. Because when i end the user's session it will be invalid.

Sorry, I guess it submitted my "first draft". Here is what I meant to post:

The token is validated against the visitor's session or csrf cookie. This means that the token is valid for the entire life time (in your case the life of the session). For most use-cases this is good enough, since the main protection is to guard against another origin with the same user's web browser making a cross-origin request (it won't know the token). The token is different for each req.csrfToken() to guard against BEAST when served over SSL.

If there is a desire to create per-page tokens, that shouldn't be too difficult to add in, so PRs welcome!

Thanks for the information and explanation. For the meantime i will limit the token to the page that was required. I will try to check if i can add a create per-page token. I'm thinking if we can add option to path on the token and path from on the request params.

By the way i'm just new on here what do you mean about this "PRs welcome!" . Sorry very noob question . Thanks

Thanks. Happy to help . I will review on how i can help. The issue per page you cannot determine where the call have been perform(which page). Do you have any idea how we can check this in express js or node?

@federomero not off-hand, which is why I was hoping for some help :)

I gave this a try - fluxsauce@7d0ef69 - and it worked within a very limited set of circumstances. If you are performing multiple POSTs on a page, such a tracking event followed by a form submission, something will fail. If you open up two browser windows, both with login forms, one of those login forms will be broken.

Kind of on the "not worth it" side of the fence right now :-(