I'm trying to prevent cross site request forgery attacks (CRFS).
Below is my token generator code on login.php.
Is this secure enough to validate the csrf token of the form against the session token?
if(empty($_SESSION['key'])){
$_SESSION['key'] = bin2hex(random_bytes(32));
}
$csrf = hash_hmac('sha256','secured:login',$_SESSION['key']);
Here is my form code on login.php -
<form action="<?php echo htmlspecialchars('log/logscript.php');?>" method="post" class="login_form">
<input type="hidden" name="csrf" id="csrf" value="<?php echo $csrf;?>">
<input type="submit" class="btn btn-login btn-block" name="submit" id="submit" value="Login">
</form>
And here is my AJAX code -
$(".login_form").submit(function(e) {
e.preventDefault();
var
sk = "<?php $csrf;?>",
fk = $("#csrf").val(),
t = $("#submit").val();
$.ajax({
url: "log/logscript.php",
type: "post",
data: {
sk: sk,
fk: fk,
submit: t
},
success: function(e) {
$(".form-msg").html(e)
}
});
});
And here is my code on log/logscript.php -
session_start();
if(isset($_POST['submit'])){
$x = $_POST['sk'];
if(hash_equals($x,$_POST['fk'])){
echo 'success';
}else {
echo 'failed';
}
}