Skip to content
Advertisement

Token for preventing CSRF attacks not validating

I am trying to add a token to my forms in order to prevent CSRF attacks

But the token validation isn’t working

Here is the input field which holds the token

JavaScript

And here is the token validation code

JavaScript

It doesn’t work and it returns the error message in the if block

Advertisement

Answer

I presume that the submitted auth_token value is something random such as hwm7wherlwkju or whatever. Testing !$auth_token could give special results, depending if it’s missing or if it contains “1”, “true” or “”. Secondly, use !== instead of != to avoid automatic type casting in the comparaison.

So I would replace your “if” condition with this:

JavaScript

About the token value generated, I think you should also check that you are not generating a new value in the session on each request before doing the comparaison for validation. The comparaison should be done first and then a new token value should be generated and stored in the session.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement