You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JMeter+BlazeMeter做性能测试时遭遇CSRF验证失败问题

JMeter性能测试解决Django CSRF错误方案

问题描述

使用JMeter搭配BlazeMeter扩展执行性能测试时,部分请求返回403 Forbidden,错误提示为CSRF cookie not set,尝试用正则表达式提取CSRF Token失败。错误页面内容如下:

<!doctype html>

403 Forbidden
Prohibido (403)

Verificación CSRF fallida. Solicitud abortada

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.

Si has inhabilitado las cookies en tu navegador, por favor habilítalas nuevamente al menos para este sitio, o para solicitudes del mismo origen.

Help

Reason given for failure:

    CSRF cookie not set.
    

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function passes a request to the template's render method.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
  • 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.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

解决步骤

1. 启用HTTP Cookie管理器

Django的CSRF验证依赖csrftoken cookie,必须在测试计划中添加HTTP Cookie管理器,让JMeter自动处理cookie的存储和发送,无需手动配置csrftoken参数。

2. 正确提取CSRF Token

Django的CSRF Token以隐藏字段形式存在于表单页面中,格式为:<input type='hidden' name='csrfmiddlewaretoken' value='xxxxxx'>

  • 将正则表达式提取器添加到返回表单页面的请求下方(不要放在错误请求下,错误页面无有效Token)
  • 提取器配置:
    • 引用名称:csrf_token
    • 正则表达式:name='csrfmiddlewaretoken' value='(.+?)'
    • 模板:$1$
    • 匹配数字:1(取第一个匹配结果)

3. 在POST请求中传递Token

在需要提交的POST请求的参数列表中添加:

  • 参数名:csrfmiddlewaretoken
  • 参数值:${csrf_token}(使用提取的Token变量)

4. 额外注意事项

  • 登录后Django会刷新CSRF Token,因此登录完成后必须重新请求表单页面,提取新的Token再进行后续POST请求
  • 确保请求的域名、路径与浏览器访问完全一致,避免跨域触发CSRF验证失败
  • 用查看结果树检查表单页面的响应数据,确认csrfmiddlewaretoken字段存在,验证正则表达式是否能正确匹配

内容的提问来源于stack exchange,提问作者Daniel Medrano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:00:58