Zubair1 Zubair1 - 2 years ago 142
PHP Question

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 - I think i've grasped the idea behind CSRF tokens but i'm having trouble finding 'good & simplified' resources and examples of Nonces.

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 mis-understanding 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.


Answer Source

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download