How to do a CSRF token request

I am trying to do a CSRF token request and have something liked this in form A and form B:

Form A:

/create a key for the hash_hmac function

  if (empty($_SESSION['key'])) {
      $_SESSION['key'] = bin2hex(random_bytes(32));
  //create CSRF Token
  $csrf = hash_hmac('sha256', 'this is some string: signup.php', $_SESSION['key']);

Sign up

Form B:

$csrf = strip_tags($_POST[‘csrf’]);

   // referral information

   $referral = strip_tags($_POST['referral']);
    $token = hash_hmac('sha256', 'this is some string: signup.php', $_SESSION['key']);

   if(!hash_equals($token, $csrf)) {
    echo "<meta http-equiv='refresh' content='0;url=../signup.php?signup2=wrongtoken'>";
                                        } else {

But I sometimes get a wrongtoken in my url and I think that the token and $csrf do not match. Have I done something wrong here?

Maybe don’t use strip_tags on the CSRF token? It could be possible that the hash_hmac function creates output which strip_tags interprets as HTML or PHP code.

Normally, input sanitation is good, but this is a simple value which either does or doesn’t match the expected value. What usage of this variable would require it to be sanitized?

I am just using a very simple session to store the openssl random pseudo bytes… hope this is good enough

I can’t get it to work either… I have something like this for each of my form page and I have about 4 form pages…:

// $csrf = strip_tags($_POST[‘csrf’]);

// if($csrf !== $_SESSION[‘key’]) {
// echo “”;

I have stored it into a session in my previous form…If i implement this, then sometimes, it won’t let me signup or complete my registration successfully…

I’m sorry, but again, why do you use strip_tags on the CSRF? Why does it need to be sanitized? It either matches or it doesn’t, so why does it matter if someone uploads some HTML code or an otherwise invalid token?

Please remove that processing of the token and then see if it still gets rejected.

I did try it without the strip tags but sometimes it work and sometimes it doesn’t work… I will keep testing it…

I think it is working for now…

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.