Implement CSRF token but without affecting navigation

0

I'm developing a web application written in PHP7. In this application, I developed a module in which it generates in the CSRF token automatically when the user "enters" on any page of the application. This is the useful part of the code for the question:

if(!isset($_SESSION['csrftoken']) || $_SERVER['REQUEST_METHOD'] === 'GET')
{
    SessionController::CriarCSRFToken(); 
}


// Na classe SessionController...
public static function CriarCSRFToken()
{
    $_SESSION['csrftoken'] = bin2hex(random_bytes(32));
}

My intention is always to perform a token check on every POST request. The useful code for the question is this:

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
    SessionController::VerificarCSRFToken();
}

//Na classe SessionController...
public static function VerificarCSRFToken()
{
    if (!isset($_POST['csrftoken']) || !hash_equals($_SESSION['csrftoken'], $_POST['csrftoken']))
    {

        //Basicamente envia a mensagem e para a execução da requisição.
        JSONResponder::ResponderFalha("Você não tem permição para acessar essa funcionalidade", true, true);
    }
}

It's working fine, however, this creates a usability problem for the application. Actions like using multiple browser tabs or just checking page source code generates update in session csrftoken. For example, I'm on tab1 with the token "abc", but then I open a new tab, tab2, the module updates the token for "bcd". There's the problem. If I try to do a POST request on tab1, the module will "deny" the request. This happens because in tab1 the token is still "abc" but when I opened the tab2 the token was "bcd".

So, how can I solve this problem? I hope I have left my question clear.

    
asked by anonymous 12.03.2018 / 17:03

0 answers