How we add CSRF protection in ajax request when we do registration or login on website ?
I try to find this subject on stackoverflow but I couldn’t get exact answer as I want and sitepoiny is my first experience community where I came for knowledge or answer I want.
Whenever I trying to implement CSRF in ajax request first errors show from CSRF offcourse it is genuinely becouse both page is diffrent.
but in security views How we make ajax so secure via CSRF or Jquery in PHP Native. How Implement Ajax CSRF in my code, please help me.
<?php
//start a session
session_start();
//create a key for hash_hmac function
if (empty($_SESSION['key']))
$_SESSION['key'] = bin2hex(random_bytes(32));
//create CSRF token
$csrf = hash_hmac('sha256', 'this is some string: index.php', $_SESSION['key']);
//validate token
if (isset($_POST['submit'])) {
if (hash_equals($csrf, $_POST['csrf'])) {
echo "Your name is: " . $_POST['username'];
} else
echo 'CSRF Token Failed!';
}
?>
<html>
<head>
<title>CSRF Tutorial by CPI</title>
</head>
<body>
<form method="POST" action="index.php">
<input type="text" name="username" placeholder="What is your name?" >
<input type="hidden" name="csrf" value="<?php echo $csrf ?>">
<input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>
I’m confused as to how you envision AJAX being involved. AFAICT this is simply an expiring token being inserted into a form, the intent being to help ensure the form is being submitted by an authorized user.
eg.
I log in as me.
An expiring token is generated for my session.
When I go to a form to edit my account details, the token let’s the script know it’s me and not someone else.
If someone else tries to edit my details the token either doesn’t match or has expired and my account details won’t be edited.
How does what you want to do differ from this? In particular, the AJAX part.
Actually I have confusion if I not add token function in my ajax form then anybody make simple form and do login on my website, So I want to protect this in this manner that my ajax url always accept my eebsite request and it only possible when we add token inside form.
If token of form(index.php) == token of ajax(call_ajax.php) then login/insert/update etc else {error : invalid tolen}
This is I want to say…
So what have you tried? I don’t see any AJAX. And within the AJAX response you can send additional debug information about what you have and what you got.