2

In php projects, I generated a csrf token, entered it into the session and later compared it with the $_POST['token'] request. One now I need this functionality for github.pages. I found how to do the same using JS. But how and with what should I now compare this parameter in the php config?

<form class="" action="https://somewhere.com/form/form.php" method="POST" id="contact_form">
    <input type="text" name="name" value="">
    <input type="email" name="email" value="">
    <input type="hidden" name="token" value="">
    <a id="submitBtn" href="#"></a>
</form>
if($_POST['token']==?????){
//code
}

And is there a php analog of the bin2hex(random_bytes(32)) function in pure JS?

1
  • Contrary to the accepted answer, yes, it is possible, see double submit cookies. Commented Mar 7, 2021 at 9:33

1 Answer 1

1

While it might be technically possible, it wouldn't be secure, since the point of a csrf token is that you can prove the form is being submitted by the same client who requested it. So the server provides the client with a secret value, that is also stored encrypted in the session. If the client sends the right value, it is proof that they also requested the page. If the client (with JavaScript) generates the token, it can't prove anything.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer! And what if I generate a token using php, send it to the user. If it matches, accept the data. Will it be safe? However, how to accept the token remotely? And can you advise some kind of alternative? Or in the case of github.pages, this is not possible, since no support for server side languages?
IIt's bee, but what you could do is render the form using PHP is put it in an iFrame. I was going to suggest putting it in the session, and making sure that the session cookie had httponly set, but more and more browsers are blocking 3rd party cookies, so if your GH pages and PHP server don't share a domain at some point (one being on a subdomain of the other), browsers might block it;
This is simply not true. See double posting as a CSRF mitigation, where the token can in fact be generated by the client, and it still prevents CSRF.
I had no idea about this, but checking it out.
but my answer still holds that it's not possible to have the client generate the token, and have it be secure. You still need the server involved to generate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.