DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on • Edited on

1

What is CSRF Token & how to use this?

CSRF stands for Cross-Site Request Forgery. It's a type of attack where a malicious website can potentially perform actions on another website where the victim is authenticated. To prevent CSRF attacks, one common technique is to use CSRF tokens.

A CSRF token is a unique, random value generated by the server and included in a form or in the HTTP headers of a request. The token is associated with the user's session and is verified by the server to ensure that the request originated from the same site and was not forged by a malicious attacker.

Here's how you can use CSRF tokens to protect your web application:

  1. Generate a Token: When a user visits your website, generate a CSRF token and associate it with the user's session. This token should be unique for each user session and should have a sufficiently long and random value to make it difficult to guess.

  2. Include the Token in Forms: When rendering forms that perform sensitive actions (such as changing user settings or making payments), include the CSRF token as a hidden field in the form.

   <form action="/change-password" method="post">
       <input type="hidden" name="csrf_token" value="...">
       <!-- Other form fields -->
       <button type="submit">Change Password</button>
   </form>
Enter fullscreen mode Exit fullscreen mode
  1. Verify the Token on the Server: When the form is submitted, the server should verify that the CSRF token included in the request matches the one associated with the user's session. If the tokens don't match or if no token is provided, the server should reject the request with an error.

  2. Protect AJAX Requests: If your application uses AJAX to make requests, ensure that the CSRF token is included in the headers of the request. You can either include the token in a custom header (e.g., X-CSRF-Token) or use a framework that automatically handles CSRF protection for AJAX requests.

   $.ajax({
       url: '/change-password',
       type: 'POST',
       headers: {
           'X-CSRF-Token': '...'
       },
       data: { /* Request data */ },
       success: function(response) {
           // Handle success
       },
       error: function(xhr, status, error) {
           // Handle error
       }
   });
Enter fullscreen mode Exit fullscreen mode

By including and verifying CSRF tokens in your web application, you can protect against CSRF attacks and ensure that sensitive actions can only be performed by authenticated users from your own site.

Support My Work ❤️

If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!

Connect with Me 🌍

Let’s stay connected! You can follow me or reach out on these platforms:

🔹 YouTube – Tutorials, insights & tech content

🔹 LinkedIn – Professional updates & networking

🔹 GitHub – My open-source projects & contributions

🔹 Instagram – Behind-the-scenes & personal updates

🔹 X (formerly Twitter) – Quick thoughts & tech discussions

I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!

Disclaimer

This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay