Ensure that your website uses secure cookies by setting the Secure attribute. This means that the browser will only send the cookie if the request is being sent over HTTPS. This helps protect the cookie from being intercepted by attackers during transit
Set-Cookie: CookieName=CookieValue; Secure
Set the HTTPOnly attribute for your cookies to prevent them from being accessed through JavaScript. This helps protect against cross-site scripting (XSS) attacks.
Set-Cookie: CookieName=CookieValue; HttpOnly
The SameSite attribute defines when cookies should be sent with cross-origin requests. Set it to “Strict” or “Lax” to prevent cross-site request forgery (CSRF) attacks.
Set-Cookie: CookieName=CookieValue; SameSite=Lax
To defeat a CSRF attack, applications need a way to determine if the HTTP request is legitimately generated via the application’s user interface. The best way to achieve this is through a CSRF token. A CSRF token is a secure random token (e.g., synchronizer token or challenge token) that is used to prevent CSRF attacks. The token needs to be unique per user session and should be of large random value to make it difficult to guess.
A CSRF secure application assigns a unique CSRF token for every user session. These tokens are inserted within hidden parameters of HTML forms related to critical server-side operations. They are then sent to client browsers.
It is the application team’s responsibility to identify which server-side operations are sensitive in nature. The CSRF tokens must be a part of the HTML form—not stored in session cookies. The easiest way to add a non-predictable parameter is to use a secure hash function (e.g., SHA-2) to hash the user’s session ID. To ensure randomness, the tokens must be generated by a cryptographically secure random number generator.
Whenever a user invokes these critical operations, a request generated by the browser must include the associated CSRF token. This will be used by the application server to verify the legitimacy of the end-user request. The application server rejects the request if the CSRF token fails to match the test.
If possible, use session cookies that expire when the user closes their browser. This reduces the window of opportunity for attackers to misuse the cookies. Or expired the cookies when user logs out