Friday 29 January 2021

Token Do Not Work On Fetch Request To PHP File

I have two files: one is exposing a session-Token, the other one is answering a javascript-fetch. File one contains:

<?php
session_start();
unset($_SESSION['sessionToken']);
$_SESSION['sessionToken'] = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));
?><!DOCTYPE HTML>
<html>
...
    <meta content="<?php echo $_SESSION['sessionToken'] ?? '12345'; ?>" name="csrf-token" />

and further on I make in the same file a fetch request like this:

fetch('src/exposeDelivery.php', {      
           //mode: 'same-origin',
           credentials: 'same-origin',     //'same-origin'    'omit'     'include
           method: 'POST',
           body: JSON.stringify( jsonArr ),
           headers: {
            'x-csrf-token':  document.head.querySelector('meta[name="csrf-token"]').content,
            "Content-Type": "application/json",
            "Accept":       "application/json"
           }
      })
        .then(response => {
          if (!response.ok) {
            console.log("response: %s  | %o",response.statusText,response);
            throw new Error('Network response was not ok');
          }
          return response.json();
        })

The fetch-request runs in an interval like let ask = setInterval(makeRequest, 20000);

My second file, where the request goes to, looks like this:

    <?php
    session_start();
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST');
    header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, x-csrf-token');
    $csrf = isset($_SERVER["HTTP_X_CSRF_TOKEN"])
          ? trim($_SERVER["HTTP_X_CSRF_TOKEN"])
          : 0;
    $response['t_token']= $csrf;
    $response['sessionToken'] = $_SESSION['sessionToken'] ? $_SESSION['sessionToken'] : "noSessionToken";

    header('HTTP/1.0 200 OK');
    header('Content-Type: application/json');

    echo json_encode($response);

Now I would like to check if $csrf == $_SESSION['sessionToken']. This is the first time I call the fetch-request true. But the second time the request is called, it is differend. What is wrong here? Is File one with the fetch-request calling itself on every request? Can I solve it with maybe another request?



from Token Do Not Work On Fetch Request To PHP File

No comments:

Post a Comment