PHP script conflicts with AJAX

the code says a thousand words

page.php? ID = 123

<?php
if(is_ajax()){// function that determines whether the request is from ajax (http header stuff)
$_SESSION['token'] = md5(rand());
}
//some ajax request to ajax.php?id=123
?>

ajax.php? ID = 123

<?php
if($_SESSION['token'] == $_GET['token']){
echo 'Tell me this is for reall';
}else{
echo 'Invalid Request';
}
?>

Does everything work fine until the user opens page.php? id = 456 on another tab, ajax returns an "invalid request" on the page. php? id = 123 How to resolve this conflict?

ps: if possible, I want a new session for each page for CSRF purposes

0
source share
3 answers

If I understand this correctly, it looks like you are setting a token for each request. I assume that the old page still has the old token. I would check if a token is installed before automatically issuing it.

 if (isset($_SESSION['token'])){
    //do nothing
 } else{
   $_SESSION['token'] = md5(rand());
 }

. .

, "", .

$_SESSION[$sessionId] = md5(rand());

, , , , , , . , . , .

.

http://www.yoursite.com/somepage.php?sessionid=<some generated id>

, , , - .

2 , , . , , , , , , , -: -)

CSFR , , , , - , , cookie Alice , , . , Alice bank http://www.mybank.com, ,

<img srg="http://www.mybank.com/transferfunds.php?amount=1000&receiver=Bob" />

- , . , (, ), ( , , ):

  • , . cookie ( " " ), . , ( ) cookie, , .
  • , - .

"" (HTTP), (1). " " .., , . (2) . ( , ) - , , .

,

$_SESSION['token'] = md5(rand());

, , .

http://www.mysite.com/secure.php?token=giuwnrefviunslfghahgliuwnvwrgbaasd

: .. cookie. , - ,

//note, you'll want to sanitize user input, I'm just being brief
if ($_GET['token'] != $_SESSION['token']){
   //User either attempted to enter a link on their own or it a CSRF attack
   header('HTTP/1.1 403 Forbidden');
 }else{
 //do whatever needs to be done
 }

, . , , , cookie . , , , . ( , , , , , , , , , , .)

, , .

+4

? JavaScript?

, , . , , . ?

+1

You need each page to start its own token, otherwise this conflict will occur.

<?php
if(is_ajax()){// function that determines whether the request is from ajax (http header stuff)
$page_id = $_GET['id'];
$_SESSION['token'][$page_id] = md5(rand());
}
//some ajax request to ajax.php?id=123
?>

and

<?php
$page_id = $_GET['id'];
if($_SESSION['token'][$page_id] == $_GET['token']){
echo 'This is for real!';
}else{
echo 'Invalid Request';
}
?>

Depending on how you implement everything, you will probably need something more complex or specialized, but this should help you get started.

0
source

All Articles