phpcsrfnonce

CSRF tokens vs Nonce confusion - are they the same?


In a attempt to make the current application I'm developing more secure, I've been reading about CSRF tokens and also Nonce.

My question simply is, Are CSRF tokens and Nonce the same thing? from what I could gather so far is that both these methods have different techniques to accomplish the same goal, or am I misunderstanding something?

If they are different, could you be nice enough to provide some example code or point me to some links where i can learn more about how to implementing nonces in PHP apps.

Thanks!


Solution

  • Nonce is usually some random string that is added to request just to change in unpredictable way the data, which is used to calculate the signature. So nonce usually is not used by any server-side business logic.

    While CSRF-token is stored somewhere on server, passed to the client and need to be returned back to the server to compare. And if matches - then OK.

    So in your case the better will be to save csrf token once in a session variable like

    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
    

    and use it unchanged during the session life in all forms you have in your application.

    (If you don't have random_bytes(), use random_compat to polyfill it.)