hi,
I am trying to redirect people that are not logged in to the login page using the very excellent access plugin.
Unfortunately it seems to collide with my csrf protection for reasons I don't understand.
I have a controller that is inherited bu all others. The before route handles the access and csrf.
For some reason my csrf token is different after a redirect.
My code:
function beforeroute() {
$csrf_page = $this->f3->get('PARAMS.0'); //URL route with preceding slash, set a csrf for every page in case other pages are opened in tabs
if ($this->f3->VERB==='POST')
{
if( strcmp($this->f3->get('POST.session_csrf'), $this->f3->get('SESSION.'.$csrf_page.'.csrf'))===0 ) // Things check out
{
$this->f3->set('CSRF', $this->f3->session->csrf()); // Reset csrf token for next post request
$this->f3->copy('CSRF','SESSION.'.$csrf_page.'.csrf');
}
else{ // DANGER: CSRF attack!
$this->f3->error(403);
}
}
else //get request: set token
{
$this->f3->CSRF = $this->f3->session->csrf();
$this->f3->copy('CSRF','SESSION.'.$csrf_page.'.csrf');
}
//the next if statement causes the problem:
if (!$this->f3->exists('SESSION.type') && strcmp($csrf_page,"/login")!=0) { //if no user type (not logged in), redirect to login, accept if already on login page (otherwise infinite loop)
$this->f3->reroute('/login');
}
$access=Access::instance();
$access->authorize($this->f3->get('SESSION.type') ); //this handles the access defined in an ini-file
}
If the problematic if statement with the redirect to the login page is deleted, everything works as expected.
Otherwise I get a 403 because of a non-corresponding csrf token, even when I went to the login page directly and no redirect was needed
Also: while trying to figure out what was wrong I came across something very weird: when I add the following in my before route:
if(null===$this->f3->get('SESSION.i')){
$this->f3->set('SESSION.i',0);
}
$session_i=1+$this->f3->get('SESSION.i');
$this->f3->set('SESSION.i',$session_i);
echo 'session.i: '.$session_i.'<br>';
Reloading the page will add not 1 but 3 or 4 to session.i !
If the redirect is added it will add 1 additional unit compared to without the redirect to login (even if the login page is simply reloaded)
I am not sure if this is related or if this is something the framework is expected to do?