Django_csrf

 

 

CSRF攻击介绍

 CSRF 攻击能够在受害者绝不知情的状况下以受害者名义伪造请求发送给受攻击站点,从而在并未受权的状况下执行在权限保护之下的操做。好比说,受害者 Bob 在银行有一笔存款,经过对银行的网站发送请求 http://bank.example/withdraw?account=bob&amount=1000000&for=bob2 可使 Bob 把 1000000 的存款转到 bob2 的帐号下。一般状况下,该请求发送到网站后,服务器会先验证该请求是否来自一个合法的 session,而且该 session 的用户 Bob 已经成功登录。黑客 Mallory 本身在该银行也有帐户,他知道上文中的 URL 能够把钱进行转账操做。Mallory 能够本身发送一个请求给银行:http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory。可是这个请求来自 Mallory 而非 Bob,他不能经过安全认证,所以该请求不会起做用。这时,Mallory 想到使用 CSRF 的攻击方式,他先本身作一个网站,在网站中放入以下代码: src=”http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory ”,而且经过广告等诱使 Bob 来访问他的网站。当 Bob 访问该网站时,上述 url 就会从 Bob 的浏览器发向银行,而这个请求会附带 Bob 浏览器中的 cookie 一块儿发向银行服务器。大多数状况下,该请求会失败,由于他要求 Bob 的认证信息。可是,若是 Bob 当时恰巧刚访问他的银行后不久,他的浏览器与银行网站之间的 session 还没有过时,浏览器的 cookie 之中含有 Bob 的认证信息。这时,悲剧发生了,这个 url 请求就会获得响应,钱将从 Bob 的帐号转移到 Mallory 的帐号,而 Bob 当时绝不知情。等之后 Bob 发现帐户钱少了,即便他去银行查询日志,他也只能发现确实有一个来自于他本人的合法请求转移了资金,没有任何被攻击的痕迹。而 Mallory 则能够拿到钱后逍遥法外。html

 

Django设置CSRF防御

全局

中间件 django.middleware.csrf.CsrfViewMiddleware

局部

from django.views.decorators.csrf import csrf_exempt,csrf_protect


@csrf_protect,为当前函数强制设置防跨站请求伪造功能,即使settings中没有设置全局中间件。

@csrf_exempt,取消当前函数防跨站请求伪造功能,即使settings中设置了全局中间件。
# FBV
@csrf_exempt
def index(request):
    if request.method == "POST":
        return HttpResponse("POST 200")


# CBV
# 方法1
urlpatterns = [
    re_path("index/$",csrf_exempt(views.Index.as_view())),
]

# 方法2 在dispatch添加@csrf_exempt/protect
class Index(View):
        # @csrf_exempt  此为无效,需在dispatch添加
    def post(self,request):
        print(request.method)
        print(request.POST)
        print(request.body)
        return HttpResponse("200 OK")

    # @csrf_exempt  此为无效,需在dispatch添加
    def patch(self,request):
        print(request.method)
        print(request.body)
        print(request.method)
        return HttpResponse("patch 200 ok")

    # @csrf_exempt  此为无效,需在dispatch添加
    def put(self,request):
        print(request.method)
        print(request.body)
        print(request.method)
        return HttpResponse("put 200 ok")

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        print("dispatch before")
        ret = super(Index, self).dispatch(request,*args,**kwargs)
        print("dispatch after")
        return ret
使用

HTML发送CSRF

1、    csrf在ajax提交的时候经过请求头传递的给后台的

二、    csrf在前端的key为:X-CSRFtoken,到后端的时候django会自动添加HTTP_,而且最后为HTTP_X_CSRFtoken

三、    csrf在form中提交的时须要在前端form中添加{%csrftoken%}

form表单提交

在form表单里面须要添加{%csrf_token%}

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="">
    {% csrf_token %}


    <div>username: <input type="text" name="username"></div>
    <div>password: <input type="password" name="password"></div>
    <input type="submit">
</form>
    <div><h3>这是csrf_token的值</h3>{{ csrf_token }}</div>

</body>
</html>
举例

 

AJAX提交

由于cookie中一样存在csrftoken,因此能够在js中经过:

$.cookie("csrftoken")获取:  headers:{ "X-CSRFtoken":$.cookie("csrftoken")},

或者
{{ csrf_token }}: data:{"usr":"root","pwd":"123","csrfmiddlewaretoken":"{{csrf_token}}"},
若是经过ajax进行提交数据,这里提交的csrftoken是经过请求头中存放,须要提交一个字典类型的数据,即这个时候须要一个key。

在views中的login函数中:from django.conf import settings,而后打印print(settings.CSRF_HEADER_NAME)

这里须要注意一个问题,这里导入的settings并非咱们在项目文件下看到的settings.py文件,这里是是一个全局的settings配置,而当咱们在项目目录下的settings.py中配置的时候,咱们添加的配置则会覆盖全局settings中的配置

print(settings.CSRF_HEADER_NAME)打印的内容为:HTTP_X_CSRFTOKEN

这里的HTTP_X_CSRFTOKEN是django在X_CSRF的前面添加了HTTP_,因此实际传递的是就是X_CSRFtoken,而在前端页面的ajax传递的时候因为不能使用下划线因此传递的是X_CSRFtoken
说明

 

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#<form action="">#}
{#    {% csrf_token %}#}
{##}
{##}
{#    <div>username: <input type="text" name="username"></div>#}
{#    <div>password: <input type="password" name="password"></div>#}
{#    <input type="submit">#}
{#</form>#}
{#    <div><h3>这是csrf_token的值</h3>{{ csrf_token }}</div>#}

<input type="button" id="btn1" value="btn1">
<input type="button" id="btn2" value="btn2">

<script src="/static/jquery.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
    $("#btn1").click(function () {
        $.ajax({
            url:"/app01/index.html",
            type:"POST",
            data:{"usr":"root","pwd":"123","csrfmiddlewaretoken":"{{csrf_token}}"},
            success:function (arg) {
                console.log("btn1")
            }
        })
    });
    $("#btn2").click(function () {
        $.ajax({
            url:"/app01/index.html",
            type:"POST",
            data:{"usr":"root","pwd":"123"},
            headers:{ "X-CSRFtoken":$.cookie("csrftoken")},
            success:function (arg) {
                console.log("btn2")
            }
        })
    })
</script>
</body>
</html>
"X-CSRFtoken":$.cookie("csrftoken") 以及 "csrfmiddlewaretoken":"{{csrf_token}}"
def index(request):
    if request.method == "GET":
        print(settings.CSRF_HEADER_NAME)  # HTTP_X_CSRFTOKEN
        return render(request,"index.html")
    elif request.method == "POST":
        print(request.POST)
        print(request.body)
        return HttpResponse("HH")
views.py

 

 

参考or转发

http://www.javashuo.com/article/p-xcptltgl-cn.html前端

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息