DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

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.

Top comments (0)