Many modern web applications use CSRF (Cross-Site Request Forgery) tokens to prevent unauthorized form submissions. These temporary, random tokens ensure that POST requests originate from a trusted source. When running load tests with LoadForge, handling CSRF tokens correctly is crucial to prevent authentication failures (such as HTTP 419 errors).

Understanding CSRF Tokens

A CSRF token is a security measure implemented by web applications to prevent attackers from forging requests on behalf of a user. These tokens are unique for each session and must be sent with every authenticated POST request.

Common CSRF Issues: If your LoadForge test is failing with an HTTP 419 error, it likely means that your request lacks a valid CSRF token.

How LoadForge Handles CSRF Tokens

To successfully simulate user actions in a test, LoadForge must:

  1. Request the login page (or any page that contains a CSRF token).
  2. Extract the CSRF token from the response.
  3. Include the token in all subsequent POST requests.

Below is an example demonstrating CSRF token handling in Laravel, but the logic applies to other frameworks as well.

Example: Handling CSRF in Laravel

from locust import HttpUser, task, between
from pyquery import PyQuery

class QuickstartUser(HttpUser):
    wait_time = between(5, 9)

    def on_start(self):
        # Step 1: Request the login page to retrieve the CSRF token
        response = self.client.get("/login")
        pq = PyQuery(response.content)
        
        # Step 2: Extract CSRF token from the login form
        csrftoken = pq("input[name=_token]").val()
        
        # Step 3: Submit login request with the CSRF token
        self.client.post("/login", data={
            "email": "user@domain.com",
            "password": "secr3t",
            "_token": csrftoken
        })

    @task(1)
    def dashboard(self):
        # Perform actions after login (e.g., accessing dashboard)
        self.client.get("/dashboard")

Explanation:

  • The on_start method fetches the CSRF token from the login page.
  • It then includes this token when making a POST request to log in.
  • Once authenticated, the user can navigate protected areas of the application.

Adapting for Other Frameworks

The same technique can be applied to Django, Flask, Rails, and other frameworks by adjusting how the CSRF token is extracted.

Example: Handling CSRF in a JSON-based API

Some APIs require the CSRF token to be included in headers instead of form data. Here’s an example:

class APIUser(HttpUser):
    wait_time = between(3, 5)
    
    def on_start(self):
        # Step 1: Get the CSRF token from headers
        response = self.client.get("/api/auth/csrf")
        csrftoken = response.headers.get("X-CSRF-Token")
        
        # Step 2: Submit login with CSRF token in headers
        self.client.post("/api/login", json={
            "username": "testuser",
            "password": "securepassword"
        }, headers={"X-CSRF-Token": csrftoken})

Debugging CSRF Issues

If your test fails due to CSRF token issues, try the following:

  1. Check if a token is required: Manually inspect the form using your browser’s Developer Tools.
  2. Ensure the token is extracted correctly: Print the extracted token before making a request.
  3. Verify headers: Some frameworks expect CSRF tokens in headers instead of form data.

Tip: If your API requires authentication, ensure that your CSRF token is included with every request after login.

Temporarily Disabling CSRF Protection for Testing

If handling CSRF tokens proves difficult, you can temporarily disable CSRF protection or allow LoadForge-specific requests through:

  • Laravel: Add an exception for LoadForge test requests in VerifyCsrfToken.php:
    protected $except = [
        'your-loadforge-test-endpoint/*'
    ];
    
  • Django: Use @csrf_exempt for test routes:
    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def test_view(request):
        # Handle test request
    
  • Allow LoadForge User-Agent or IPs: Some web applications allow specific user agents or IP addresses to bypass CSRF checks.

Warning: Disabling CSRF should only be done for testing purposes and never in a production environment.

By correctly handling CSRF tokens—or temporarily disabling them where necessary—you can ensure smooth and accurate load testing with LoadForge.