How to prevent CSRF

SahandAmi
2 min readFeb 6, 2021

--

before read this article you have to know that how CSRF works

there is three main solutions to prevent the CSRF (Cross-Site Request Forgery)

1-prevent CSRF with adding a token to state-change requests

— — — — — — — but what is state-change request?! — — — — — — —

for example: someone is changing his password in a website and he is logged in , he is doing an state-change .

here the pass change request should have a token to prevent CSRF.

in this case if we remove the token header the process will be false cause this site configured this security mechanism in a correct way.

in some cases we can bypass token (:

1-give a null token

2-give an empty token

3-remove token parameter

4-token replace (random)

5-token replace (our token)

… — >if wanna know more search about it :)

2-prevent CSRF with checking referer header:

also another way its to check the referer header of the state-change requests.

with this solution, we can broke the access to change password page, when script running from another origin . but should to configure it safely, cause also we can bypass some cases using:

— — — — — — — — — — — — — — — — — — |

POST /change-pass/ HTTP/1.1

host:www.domain.tld

referer: domain.tld

— — — — — — — — — — — — — — — — — — |

the web site checks that if ‘domain.tld’ was in the referer user can change his pass…

so (:

  • referer: domain.tld.hacker.com
  • referer: hacker.com/domain.tld
  • referer: domain.tldhacker.com

here the domain.tld is in the referers but the site is for hacker , now referer check bypassed.

3-prevent CSRF with adding custom header:

Actually when we add a custom header we converted simple request to preflight request and csrf with preflight request is imposible.

ex:

x-header: hello

Access-Control-Allow-Headers: X-header

now we have preflight request and nobody can’t use CSRF here…

--

--