Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65883878/token-do-not-work-on-fetch-request-to-php-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appears you are unsetting $_SESSION['sessionToken'] variable, so it generates new value every time. Remove 3rd line in first file and you are good to go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...