CSRF FAIL WITH JMETER

I have a problem with JMeter. I am trying to perform performance tests with the BlazeMeter extension. When making some requests, I get an error with the CSRF. I already tried extracting the token with a regular expression extractor, but it doesn't find it.

  <!doctype html>
<html lang="en">
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="robots" content="NONE,NOARCHIVE">
  <title>403 Forbidden</title>
  <style type="text/css">
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; background:#eee; color:#000; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; margin-bottom:.4em; }
    h1 span { font-size:60%; color:#666; font-weight:normal; }
    #info { background:#f6f6f6; }
    #info ul { margin: 0.5em 4em; }
    #info p, #summary p { padding-top:10px; }
    #summary { background: #ffc; }
    #explanation { background:#eee; border-bottom: 0px none; }
  </style>
 </head>
 <body>
  <div id="summary">
   <h1>Prohibido <span>(403)</span></h1>
   <p>Verificación CSRF fallida. Solicitud abortada</p>
   <p>Estás viendo este mensaje porqué esta web requiere una cookie CSRF cuando se envían formularios. Esta cookie se necesita por razones de seguridad, para asegurar que tu navegador no ha sido comprometido por terceras partes.</p>
   <p>Si has inhabilitado las cookies en tu navegador, por favor habilítalas nuevamente al menos para este sitio, o para solicitudes del mismo origen.</p>
  </div>
  <div id="info">
   <h2>Help</h2>
   <p>Reason given for failure:</p>
   <pre>    CSRF cookie not set.
    </pre>
   <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/2.1/ref/csrf/">Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p>
   <ul>
    <li>Your browser is accepting cookies.</li>
    <li>The view function passes a <code>request</code> to the template's <a href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> method.</li>
    <li>In the template, there is a <code>{% csrf_token %}</code> template tag inside each POST form that targets an internal URL.</li>
    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code> template tag, as well as those that accept the POST data.</li>
    <li>The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.</li>
   </ul>
   <p>You're seeing the help section of this page because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and only the initial error message will be displayed.</p>
   <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
  </div>
 </body>
</html>

I tried to create this regular expression

enter image description here

Using regular expressions for getting values from HTML responses is not the best idea, if the token is in the response body the most obvious choice is CSS Selector Extractor

And you need to apply the extractor to the Sampler where the token appears in the response, see Scoping Rules user manual entry

If you need more comprehensive help you need to share at least partial response where the token appears, this way we'll be able to come up with proper Post-Processor setup.

In the meantime I can only suggest to get familiarized with What is CSRF & How to Load Test CSRF-Protected Websites article

This typically happens when the CSRF token is missing or incorrect in the request. Here’s how you can resolve this issue step-by-step:

1. Ensure CSRF Token is Extracted Correctly

First, make sure you are correctly extracting the CSRF token from the responses of your application. You can use the Regular Expression Extractor in JMeter for this purpose. Here’s how:

  1. Add a Regular Expression Extractor to the request that loads the page containing the CSRF token.

    • Field to check: Body
    • Regular Expression: name='csrfmiddlewaretoken' value='(.+?)'
    • Template: $1$
    • Match No.: 1
    • Reference Name: CSRF_TOKEN
  2. Ensure that you have a Response Assertion to validate that the CSRF token is present in the response body.

2. Use the Extracted Token in Subsequent Requests

Next, you need to use the extracted CSRF token in the subsequent requests:

  1. In the HTTP Request where the CSRF token is required, add the token to the request parameters:
    • Name: csrfmiddlewaretoken
    • Value: ${CSRF_TOKEN}

3. Debugging Tips

  • Check if Cookies are Handled Properly: CSRF tokens often rely on cookies. Ensure you have an HTTP Cookie Manager added to your Test Plan to manage cookies.
  • Validate the Token Extraction: Add a Debug Sampler and a View Results Tree listener to verify that the CSRF token is being extracted and passed correctly.
  • Reload the Page if Necessary: Sometimes, the CSRF token might change after certain actions (e.g., login). Ensure you are reloading the necessary pages to get the updated CSRF token.

4. Example Configuration

Here’s a simplified example of how your Test Plan could look:

  1. HTTP Request Sampler (Load Page with CSRF token)

    • URL: http://your-website.com/form-page
    • Add a Regular Expression Extractor to extract the CSRF token.
  2. Debug Sampler (Optional)

    • To verify the extracted token.
  3. HTTP Request Sampler (Submit Form)

    • URL: http://your-website.com/submit-form
    • Add Parameters:
      • csrfmiddlewaretoken: ${CSRF_TOKEN}
      • (Other form parameters)
  4. Listeners

    • Add View Results Tree to see the request and response details.

5. Example Regular Expression Extractor Configuration

  • Name: Extract CSRF Token
  • Apply to: Main sample and sub-samples
  • Field to check: Body
  • Reference Name: CSRF_TOKEN
  • Regular Expression: name='csrfmiddlewaretoken' value='(.+?)'
  • Template: $1$
  • Match No: 1
  • Default Value: NOT_FOUND

6. Example HTTP Request with CSRF Token

  • Name: Submit Form
  • URL: http://your-website.com/submit-form
  • Parameters:
    • Name: csrfmiddlewaretoken
    • Value: ${CSRF_TOKEN}
    • (Other form parameters)

By following these steps, you should be able to properly extract and use the CSRF token in your JMeter tests, thereby avoiding the 403 Forbidden error related to CSRF verification.

Back to Top