📝CSRF (Cross-site request forgery)

CSRF is a web security that relies on malicious webpage sending requests to the other domain.

This is an issue if all above applies:

  • authorization is purely cookies-based (there is no other tokens)
  • all request parameters are predictable
  • there is an action that must be secured

When a webpage issues a request to another domain (e.g., with a form), the browser automatically includes domain-specific cookies, so the request will be authorized.

CSRF tokens

To prevent CSRF (Cross-site request forgery) attack, the most common method is to use CSRF tokens—unique, secret, unpredictable tokens. The token must be generated on the server side and transferred to the client. They should be stored with user session and checked on every request—if submitted token does not match session one (or is absent), the request is unauthenticated.

How to transfer CSRF tokens

  • They can be transferred in body
  • Can be transferred in query params (less secure because urls are logged in multiple places)
  • They must not be transferred in cookies
  • Transferring them in a custom header is more secure because browsers usually don’t allow sending custom headers cross-domain. This limits tokens to XHR only (no html forms).

SameSite cookies

SameSite cookies can also be used to prevent CSRF (Cross-site request forgery) attack. Setting SameSite for a cookie instructs the browser to not include the cookie if request has originated from another site.

SameSite=Strict is the most defensive option. The downside is that it will not send the cookie if user followed a link from another site, so the user will appear logged out and will have to login again.

SameSite=Lax is a more relaxed options and will include cookie if both hold:

  • The request is a GET request
  • The request originated from top-level navigation by the user (e.g., clicking a link). Request initiated by scripts will not include the cookie.

SameSite=Lax cookies provide partial defense against CSRF (Cross-site request forgery). CSRF is still possible if the app executes some sensitive actions on GET requests. Therefore, it is not recommended to rely on SameSite cookies as the only defense mechanism.

Reference

Want to receive my 🖋 posts as I publish them?