What are CSRF tokens? - cereal-d3v/Molecularium-NanoSpace GitHub Wiki

How CSRF Tokens Work

What is CSRF?

CSRF (Cross-Site Request Forgery) is a type of security vulnerability where an attacker tricks a user’s browser into making unwanted actions on a web application in which the user is authenticated. This can lead to unauthorized actions such as changing account details or making purchases.

How CSRF Tokens Prevent Attacks

A CSRF token is a unique, unpredictable value generated by the server and associated with the user's session. It is included in forms and AJAX requests that modify data. When the server receives a request, it checks that the token matches the one it issued. If the token is missing or invalid, the request is rejected.

This prevents attackers from forging requests, because they cannot guess or obtain the correct token.

How It Works in Practice

  1. Token Generation:
    When a user visits a page, the server generates a CSRF token and stores it in the user's session.

  2. Token Inclusion:
    The token is embedded in HTML forms as a hidden field or in a meta tag for JavaScript to use in AJAX requests.

    Example in HTML:

    <input type="hidden" name="authenticity_token" value="random_token_value">
    

    Example in a meta tag:

    <meta name="csrf-token" content="random_token_value">
    
  3. Token Submission:
    When the user submits a form or makes an AJAX request, the token is sent to the server.

  4. Token Verification:
    The server checks if the submitted token matches the one stored in the session. If it matches, the request is processed. If not, the request is rejected.

Example: Rails CSRF Protection

Rails includes CSRF protection by default. It adds a CSRF token to all forms and expects it in all non-GET requests.

  • In the layout:

    <%= csrf_meta_tags %>
    
  • In JavaScript (for AJAX):

    var csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    $.ajaxSetup({
      headers: { 'X-CSRF-Token': csrfToken }
    });
    

Best Practices

  • Always enable CSRF protection in your web framework.
  • Ensure all state-changing requests (POST, PUT, DELETE) require a valid CSRF token.
  • Never expose CSRF tokens to third-party sites.

References