DEV Community

Rounit Ranjan Sinha
Rounit Ranjan Sinha

Posted on

Understanding CSRF in Web.

As a web developer one needs to understand about Web Security,
Let's talk about Cross-Site Request Forgery (CSRF), with a common example.

Suppose you are single (us bros us) and want to enter a pub, but only couples are allowed. You tried, but the bouncers outside the pub gave you some kicks on your *** (less than your ex). Then you see a girl outside the pub who wants entry but is not allowed. You both pair up and then get entry inside that pub. After the party is over, you both move out from there with exchanged phone numbers 😉.

Chalo bht hua, ab tech smjho!

Here's an example of a CSRF attack:

Let's say Rounit is browsing a social media platform called "SocialBook," where users can post messages on their profiles. When users submit a new post, the platform sends a POST request to the server to save the message.

Now, suppose Rounit is logged into SocialBook(means authenticated) and comes across a malicious website while browsing the internet. This malicious website contains hidden code that automatically submits a form to create a post on Rounit's SocialBook profile without his knowledge or consent.

Here's how the attack unfolds:

  1. Rounit is logged into SocialBook and visits the malicious website.
  2. The malicious website includes a hidden form that targets SocialBook's post creation endpoint with predefined values: <form action="https:/anylink" method="post"> <input value="Check out this website!"> </form>.
  3. The attacker uses JavaScript to automatically submit the form in the background without Rounit's awareness.
  4. Rounit's browser, following the attacker's instructions, sends a POST request to SocialBook's post creation endpoint with the predefined message.
  5. SocialBook's server receives the request and treats it as a legitimate request because it appears to originate from Rounit's session.
  6. The malicious message gets posted on Rounit's profile without his knowledge or consent.

In this example, the CSRF attack tricks Rounit's browser into making a request on his behalf to perform an unintended action—creating a post on his SocialBook profile—by exploiting the trust relationship between Rounit's browser and SocialBook.

To protect against CSRF attacks, SocialBook can implement measures such as CSRF tokens, to ensure that requests originated from forms embedded on their own website rather than from external sources.

To protect against CSRF attacks, Implement CSRF tokens: Use unique tokens in each HTML form or request that performs sensitive actions. The token should be generated server-side and embedded within the form or included as a header in AJAX requests.

Follow #rounitsinha for more such contents

Top comments (0)