Reputation: 3543
my ajax code is:
$.ajax({
type: "POST",
url: "save.php",
data: {
name: $(this).attr('name'),
value: $(this).val(),
id: <?php if(!empty($_SESSION['user'])) echo $_SESSION['user'];?>
}
});
and in save.php i'm checking with this condition:
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SESSION['user']!=$_POST['id']){
//then show an error
}
is this the correct method to prevent unauthorized call to save.php?
Upvotes: 2
Views: 1036
Reputation: 11999
In general..
Anything at the client side is insecure. Therefore, any script may be called from anybody at any time using any set of parameters.
Protecting specific script
Therefore, we need to prepare something at the server-side, that verifies something as valid at a later point of time.
Let's call it a security-token. A security-toke needs to be sufficiently long and random string. The security-token need to be non predictable. In this case, only the server-side application can be the source of this token.
Save this security-token to the user's session and pass it along to the client. Associate the security-toke with the script call to be protected. Your session might have this property:
$_SERVER[ 'sys$securityTokens' ]
= array(
'AHSsd67sdSJDH/D6wehsd'
=> array( 'script' => 'sensibleScript.php',
'params' => array( 'kid' => 3, 'var5' => 12 )
),
'KSD87sd78sdsfk(DDF/sd'
=> array( 'script' => 'someOhterSensibleScript.php',
'params' => array( 'value' => 'welcome!' )
)
);
Note, that this structure associates security-tokes with script-names and valid parameters to be called later on.
If client needs to call the script using JavaScript, it passes the security-token back to the server.
At the server side...
If a sensible script request comes in and the correct security-token is part of the request, remove the security-token from the session and execute the script.
If a sensible script request comes with no security-token, reject the request.
Upvotes: 4
Reputation: 1179
As i see what you are tying to do..
better do it this way:
$.ajax({
type: "POST",
url: "save.php",
data: {
name: $(this).attr('name'),
value: $(this).val(),
id: <?php if(!empty($_SESSION['user'])) echo $_SESSION['user'];?>
}
});
and in save.php check with this condition:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest' || $_SESSION['user']!=$_POST['id']){
//here you can show an error
}
This new condition will also check weather the request made was through ajax or not ?
As you can see its not a real restriction of user. it would be better if you do it serverside. you can have a look at this Restrict direct page access
Its secure but there are more ways out there too..
Upvotes: 1