Cross-Site Request Forgery (CSRF)

About CSRF: Attacker designs a webpage that sends requests to a vulnerable website for action like change in password, etc. Now, if a user who is pre-logged-in to the vulnerable website, comes to the attacker’s webpage and does the action, the attacker can send his own parameters in the request to the vulnerable site. Thus, the attacker sends a cross-site request, forging it with his own parameters. Hence the name, CSRF.

Defending against CSRF

There is no silver bullet to defend against this attack. We list out good practices which help in avoiding CSRF vulnerability on your website.

The web server sets a CSRF cookie in GET request. Further, in all the POST (or other transaction) requests, a CSRF parameter is passed in headers or as a hidden form parameter. The server validates the CSRF parameter value and the CSRF cookie value according to the algorithm and a secret, both only known to the server. This technique of validation is called the Double submit cookie technique. The attacker will not be able to send the correct CSRF token and CSRF cookie pair, thus the server will reject the request.

Signed Cookies

Both the CSRF cookie and the user authentication cookie should be signed using a secret only known to the server. This prevents the attacker from manipulating the value of the cookies because he will not be able to correctly sign them.

Both the CSRF cookie and the user authentication cookie should have the following attributes set:

  • The SameSite cookie attribute should be set to either Strict or Lax. None should be avoided. This prevents forwarding these cookies from the attacker's webpage to the web server.
  • The Secure cookie attribute should be set to true. This prevents cookies to be forwarded to HTTP connections.
  • The httpOnly cookie attribute should be set to true. This prevents the accessibility of these cookies in frontend JS.

Read more about these attributes on MDN Web Docs.

To mitigate CSRF risk, we can use popular libraries available in various languages and frameworks, to avoid re-inventing the wheel. Following are some examples.

Language Framework CSRF protection package
Node.js Express csurf NPM package
Node.js Koa koa-csrf NPM package
Golang Gin, Goji, Echo gorilla/csrf from
gorilla toolkit


In this blog, we discussed CSRF attacks and how they can be mitigated. If you want help in eliminating this vulnerability, you can get in touch with PLG Works, that’s us.

Kedar Chandrayan

Kedar Chandrayan

I focus on understanding the WHY of each requirement. Once this is clear, then HOW becomes easy. In my blogs too, I try to take the same approach.