Protecting Against CSRF with Session Id

Many web applications are susceptible to Cross-Site Request Forgery (CSRF) attacks, where an attacker tricks a user into performing actions they did not intend to. One common defense against CSRF attacks is to use a session id. However, a question arises – couldn’t the page’s JavaScript simply insert the session id from the cookie into the body of each HTTP request?

The answer is no. While it may seem like a simple solution, this approach does not provide sufficient protection against CSRF attacks. Instead, a more robust solution is to use a separate cookie containing the anti-CSRF token, which is accessible to page JavaScript.

When the client logs in, two cookies are set – one HttpOnly session id cookie and one non-HttpOnly anti-CSRF token cookie, which can be accessed by page scripts. The server stores the anti-CSRF token value along with the client session id and validates that it matches the value originally set via the second cookie. If the validation fails, a potential CSRF attack is detected.

This approach, also known as the double-submit cookie scheme, provides an effective defense against CSRF attacks. It ensures that each request includes a valid anti-CSRF token, making it difficult for attackers to forge requests without access to the token.

Leave a Reply

Your email address will not be published. Required fields are marked *