CodeIgniter Forums
CI4 csrf_field not generate same value as csrf_hash - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: CI4 csrf_field not generate same value as csrf_hash (/showthread.php?tid=76615)



CI4 csrf_field not generate same value as csrf_hash - nmaa3003 - 06-02-2020

I'm trying to implement csrf validation in my form.
based on my understanding, we just compare the csrf hash from view/post with the csrf in backend/controller.
so, i tried to use 

Code:
<?= csrf_field() ?>
 in my view page, then do some comparison
Code:
if ($this->request->getPost(csrf_token()) === csrf_hash()) {
#do some stuff
}
result: the hash value is different.
but it wont be an issue if i use 

Code:
csrf_token() and csrf_hash()
 in the form. the hash generated always same.
how to solve this or do the validation bt using the csrf_field? as per documentation, it only stated the way we can retrieve the value with the same exact thing that I've done.
fyi, I'm not using 

Code:
form_open()
 as i would prefer to do the html by myself with some bootstrap.


RE: CI4 csrf_field not generate same value as csrf_hash - jreklund - 06-02-2020

You need to store the value in a cookie or session to match it against the post.

Take a look at the CSRFVerify() function in system/Security/Security works.


RE: CI4 csrf_field not generate same value as csrf_hash - dave friend - 06-02-2020

Have you looked at the Security Class documentation? The functionality to use CSRF is already builtin.