In this section, we will address the issue of misusing cookies, focusing on cross-site request forgery. Let’s consider a scenario where a user interacts with a browser and intends to visit a bank’s website, the user sends a login request and receives a cookie from the bank as a result. This cookie allows the user to perform further operations on the site, assuming the login was successful. However, if the user is tricked in to visiting a malicious website, such as http://www.dangerous.com, and the dangerous site sends a request to bank on behalf of the user, the user’s cookie associated with the bank is sent along with it. Unfortunately, this is how browsers function, and if the bank is not cautious, the dangerous site can initiate transactions on behalf of the user without the user’s awareness.
To mitigate this risk, there are two protections available in the .NET Core world:
- Antiforgery Tokens
- SameSite cookies
Antiforgery Tokens are implemented using the form tag helper in ASP.NET. While it appears to be a regular form tag, it generates additional code, including a hidden input field containing a token. This token ensures that only forms generated by ASP.NET itself can be successfully submitted, rejecting any requests without the proper token. To enhance the effectiveness of the Antiforgery token mechanism, controller’s actions must be decorated with the validate Antiforgery token attribute. Even if the dangerous site sends a token on behalf of the user, the absence of the Antiforgery token generated by the ASP.NET form will result in the request being rejected, keeping the user safe.
Another approach to address cross-site forgery is the usage of SameSite Cookies.
These special cookies can only be sent directly to the bank and not from a third-party website. Samesite cookies work by distinguishing between their path and regular cookies. When a user send a request, the receive both a regular cookie and a SameSite cookie. The SameSite cookie behaves differently than the regular cookie. When the user visits a website like http://www.dangerous.com, only the regular cookie will be sent to the bank’s website, while the SameSite cookie remains protected by the browser itself. This provides effective solution to prevent cross-site request forgery.
For further reference and more detail information, you can visit the following link: