Handling CSRF Tokens
How to support CSRF tokens in LoadForge tests, including Laravel integration.
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:
- Request the login page (or any page that contains a CSRF token).
- Extract the CSRF token from the response.
- 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
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:
Debugging CSRF Issues
If your test fails due to CSRF token issues, try the following:
- Check if a token is required: Manually inspect the form using your browser’s Developer Tools.
- Ensure the token is extracted correctly: Print the extracted token before making a request.
- 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
: - Django: Use
@csrf_exempt
for test routes: - 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.