đź“ť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:

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

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:

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.