这是正确的方法吗?我读到使用会话并不安全。
表单请求
<?php
session_start();
$_SESSION['HTTP_X_CSRF_TOKEN'] = bin2hex(random_bytes(32));
?>
<meta name="csrf-token" content="<?php echo $_SESSION['HTTP_X_CSRF_TOKEN']; ?>">
<script>
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'post',
url: 'response.php',
data: data
...
</script>
页面响应
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
if (isset($_SERVER['HTTP_X-CSRF-TOKEN']))
{
if ($_SERVER['HTTP_X-CSRF-TOKEN'] !== $_SESSION['HTTP_X_CSRF_TOKEN'])
{
exit(json_encode(['error' => 'Wrong CSRF token.']));
}
}
else
{
exit(json_encode(['error' => 'No CSRF token.']));
}
...