getkirby-v2 / toolkit

This is the deprecated toolkit for Kirby v2.
http://getkirby.com
81 stars 50 forks source link

csrf() helper: Support for multiple executions per page #242

Closed lukasbestle closed 7 years ago

lukasbestle commented 7 years ago

From #240:

This is not the same thing, but also about csrf(): if you use it multiple times on a page (i.e. when you have two forms on one page) it resets the token every time you call the function.

This could solve that:

function csrf($check = null) {

  // make sure a session is started
  s::start();

  // make sure to generate one token per page
  static $token;

  if(is_null($check)) {
    if(!$token) { 
      $token = str::random(64);
      s::set('csrf', $token);
    }
    return $token;
  }

  return ($check === s::get('csrf')) ? true : false;

}

Still has the null issue ofcourse :)

lukasbestle commented 7 years ago

This is now fixed on the develop branch. I have also decided to generate only one CSRF token per session and not per request. This doesn't reduce security by a lot but improves UX as the browser back button and AJAX/fetch requests won't kill the token validity.