CSRF (Cross-Site Request Forgery) Explained

How does a CSRF attack work?

A CSRF attack targets users that are authenticated to a vulnerable website. Through this attack, an attacker can take the identity of a user and perform an action on their behalf. These actions will then appear to the website as if they were performed by the legitimate user.



In this example, the website allows state changing operations using the GET method. Such websites are a golden mine for a malicious actor. Since the GET method contains the parameters in the link, the attacker will only have to send a forged link to a legitimate user as we did here.


As the above process shows, what makes this attack vector possible is the trust that the website has in the browser.


The impact of CSRF can be devastating for any organization having a website that is vulnerable to this attack. They might have their reputation tarnished, users may become mistrustful of them, and they may even run the risk of incurring regulatory fines.

How to protect against CSRF?

Thankfully, your website doesn’t have to be vulnerable to this attack. There are some good practices that you can implement if you want to protect your website against CSRF.

  • A website should not permit state-changing operations based on GET requests.
  • Always limit session duration for connected users. Websites should terminate sessions whenever users leave the website.
  • Cross-Site Scripting (XSS) prevention controls should also be implemented, since XSS can be used to exploit CSRF.

CSRF Tokens

Use anti-CSRF tokens with every request that changes a state in the website. The web application should generate these tokens on the server-side and their value should be unpredictable. If a malicious user attempts a CSRF attack, they will never be able to change a state on the website since their request would need to include the associated token, which they do not know.

SameSite Cookie

The SameSite cookie attribute will prevent cookies from being sent in cross-site requests. A website should specify within its response header “Set-Cookie” the value of SameSite to Lax or Strict. This will prevent the browser from sending the session cookie to the website with requests originating from other websites.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store