Django | 从中间件的角度理解跨站请求伪造(Cross-Site Request Forgey)[CSRF攻击]

文章目录

切入点

某些恶意网站上包含链接、表单按钮或者]avaScript,它们会利用登录过的用户在浏览器中的认证信息试图在你的网站上完成某些操作

  • Gjango如何做?

存储暗号:html页面一个 ||| COOKIE 一个

Django在一定的运算下比对两个暗号 是一致的 就不会发生403错

我们通过一个案例来理解

案例测试

确保CSRF中间件功能已经启动

views.py测试代码

python 复制代码
def test_csrf(request):
    if request.method == 'GET':
        return render(request, 'test_csrf.html')
    elif request.method == 'POST':
        return HttpResponse('---test post is ok---')

templates模板下的html文件

  • 注意此时 html没有暗号
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test_csrf</title>
</head>
<body>

    <form action="/test_csrf" method="post">

        <input type="text"  name="username">
        <input type="submit"  value="提交">

    </form>
</body>
</html>

配置路由

path('test_csrf',views.test_csrf),

运行服务 出现CSRF报错

python manage.py runserver

  • 网页查看

    网页报错403,CSRF验证失败,同时给出了我们具体的解决方案

解决CRSF报错

  • html添加暗号
html 复制代码
    <form action="/test_csrf" method="post">
        {% csrf_token %}   
        <input type="text"  name="username">
        <input type="submit"  value="提交">

    </form>

{% csrf_token %}是CRSF能否验证通过 的关键

再次运行服务 查看结果

  • 检查查看cookie
  • 查看html界面源码

    出现暗号 但是隐藏了
    到这里,你应该进一步理解了CSRF攻击的原理了吧
相关推荐
染指111010 小时前
128.Agent-LangChain核心组件-中间件-调用模型的时候
人工智能·windows·中间件·langchain·agent
言乐615 小时前
Python实现ai进化
python·django·virtualenv·pygame·tornado
染指111021 小时前
129.Agent-LangChain核心组件-自定义中间件-通过类实现(AgentMiddleware)
人工智能·中间件·langchain·agent·agents
言乐62 天前
Python排名统计折线图
开发语言·python·django·virtualenv·pygame
程序猿乐锅2 天前
【黑马点评 | 第九篇】秒杀优化-异步实现
java·spring boot·redis·后端·spring·中间件·mybatis
Wx-bishekaifayuan2 天前
springboot户外登山社交小程序19787-计算机课程设计、毕业设计
spring boot·后端·python·spring·elasticsearch·django·课程设计
FYKJ_20102 天前
springboot刑事案件管理系统03047-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_20102 天前
springboot助农产品销售商城05829-计算机课程设计、毕业设计
java·spring boot·python·mysql·spark·django
Wx-bishekaifayuan2 天前
springboot社区扶贫救助管理系统13300-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan2 天前
springboot甘肃特产服务平台50301-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游