Hi guys,
I am building a new project with this excellent framework.
I
am implementing csrf on my pages. In stead of manually adding it on
every single page and in every single controller I thought to do this in
my
beforeroute function of my standard controller which extends all other controllers ("one controller to rule them all"!)
This seems to work pretty well, but I am uncertain of any unexpected behavior I have not thought about.
Is it good practice to do things this way?
My code is as follows:
index.php:
...
$f3->set('CACHE', true);
$f3->session = new Session();
$f3->run();
Controller (which extends all other controllers):
function beforeroute() {
if( NULL === $this->f3->get('POST.session_csrf') || //for pages with no forms on them
((NULL !== $this->f3->get('POST.session_csrf')) && // check is csrf is posted, if so: next line
($this->f3->get('POST.session_csrf') == $this->f3->get('SESSION.csrf') ) ) // if the csrf is posted, check if it corresponds to the session csrf
)
{ // Things check out! No CSRF attack was detected.
$this->f3->set('CSRF', $this->f3->session->csrf()); // Now reset csrf token for inclusion in the page we are about to load
$this->f3->copy('CSRF','SESSION.csrf'); // copy the token to the variable
}
else{ // DANGER: CSRF attack!
$this->f3->set('ERROR.text', "Something went terribly wrong!"); // this line does not work
$this->f3->set('ERROR.code', 405); // I am not sure if this is the correct HTTP code to use.
$this->f3->reroute('/error');
}
}
In my forms i add:
<input type="hidden" name="session_csrf" value="{{ @CSRF }}" />
This seems to work very well, but is this a good way of handling this?
Also: setting the ERROR message and code does not seem to work. Is this not possible doing it this way?
I always get a 404 error with the above code.