Let’s say a user wants to delete a post and you want to perform this asynchronously, you’d probably do something like…
$.post('https://mysite.com/execs/remove.php?&post_id=' + post);
Or you wouldn’t, because you don’t want someone to be able to just copy that link with the user’s post id and trick them into deleting it. So instead I do this…
$.post('https://mysite.com/remove.php?post_id=' + post + '&visit_session=' + visit_session);
I plugin their secret visit session id which is called via ajax earlier in the script and changes every time they login. So unless a user can guess their random id the link will fail and the user will be safe…
Then I wondered what’s stopping someone from creating a webpage to steal this user’s visit session id? Couldn’t a malicious person essentially just copy and paste my ajax request in their own site and do something like this…
$.ajax({
type: 'GET',
url: 'https://mysite.com/visit_session.php',
dataType: 'json',
success: function(data) {
window.location = "https://mysite.com/remove.php?post_id=POSTID&visit_session=' + data.visit_session";
}
});
So if a user set up a site with that little script in it, and then linked it to the user they wanted to trick into deleting their post, wouldn’t it do just that? (Assuming the user is currently logged into my site).
Assuming I’m right in my thinking here, what can I do to prevent this from happening?
EDIT: Instead of polling the visit session variable inside my javascript file I know I could just do something like…
<script>
visit_session = "<?php echo $_SESSION['visit'] ?>";
</script>
<script src="https://mysite.com/javascript/main.js"></script>
This would prevent a malicious user from polling it on behalf of another user. However I’d rather avoid having to add that to every page and just keep it all in the main.js file if possible. So if anyone has any suggestions or tips I would appreciate it.
No, this is not possible. XMLHttpRequest forbids the access to the response of cross-origin requests unless the server explicitly allows it according to Cross-Origin Resource Sharing.
So this piece of code run at a different origin won’t be able to read
dataunless the server explicitly allows the different origin to do so. The latter would be the case if the server responds withAccess-Control-Allow-Origin: *which allows any origin to share the response.