xone

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

get这个网页的时候,网页里会嵌入一段随机字符串,post提交网页里的数据时,带着这个随机字符串一起提交到后台,如果没有这个随机字符串就会提交不成功。

 

ajax的csrf验证

视图函数:

def login(request):

    if request.method == 'GET':
        return render(request,'login.html')
    elif request.method == 'POST':
        user=request.POST.get('user')
        password = request.POST.get('password')
        if user == 'root' and password == '123':
            request.session['is_login'] = True
            request.session['username'] = user
            if request.POST.get('expire')== '1':
                request.session.set_expiry(10)

            return redirect('/index/')
        else:
            return render(request,'login.html')

def index(request):
    if request.session.get('is_login',None):
        # return HttpResponse(request.session['username'])
        return render(request,'index.html')
    else:
        return redirect('/login/')

方法一:

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <form id="f1" action="/login/" method="POST">
        {% csrf_token %}

        <input type="text" placeholder="user" name="user">
        <input type="password" placeholder="password" name="password">
        <input type="checkbox" value="1" name="expire"> 10秒免登陆
        <input type="submit" value="提交">
        <input id="btn" type="button" value="按钮">

    </form>

    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    <script>

        $(function () {

            $('#btn').click(function () {
                $.ajax({
                    url:'/login/',
                    type:'POST',
                    data:{'user':'root','password':'123'},
                    headers:{'X-CSRFtoken': $.cookie('csrftoken')},  //局部配置
                    success:function (arg) {
                        location.href='/index/'
                    },
                    error:function () {
                        alert('error')
                    }
                })
            })
        })
    </script>

</body>
</html>

方法二:

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <form id="f1" action="/login/" method="POST">
        {% csrf_token %}
        <input type="text" placeholder="user" name="user">
        <input type="password" placeholder="password" name="password">
        <input type="checkbox" value="1" name="expire"> 10秒免登陆
        <input type="submit" value="提交">
        <input id="btn" type="button" value="按钮">
    </form>

    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    <script>

        $(function () {

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
            
            $.ajaxSetup({    //全局配置
                beforeSend: function (xhr,settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {    //判断请求类型
                        xhr.setRequestHeader('X-CSRFtoken', $.cookie('csrftoken'))
                    }
                }
            });

            $('#btn').click(function () {
                $.ajax({
                    url:'/login/',
                    type:'POST',
                    data:{'user':'root','password':'123'},
                    success:function (arg) {
                        location.href='/index/'
                    },
                    error:function () {
                        alert('error')
                    }
                })
            })
        })
    </script>

</body>
</html>

 

方法三:??

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <form id="f1" action="/login/" method="POST">
        {% csrf_token %}

        <input type="text" placeholder="user" name="user">
        <input type="password" placeholder="password" name="password">
        <input type="checkbox" value="1" name="expire"> 10秒免登陆
        <input type="submit" value="提交">
        <input id="btn" type="button" value="按钮">

    </form>

    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    <script>

        $(function () {
            
            $('#btn').click(function () {
                $.ajax({
                    url:'/login/',
                    type:'POST',
                    data:$('#f1').serialize(),  //直接从form里获取到csrf进行提交
                    success:function (arg) {
                        location.href='/index/'
                    },
                    error:function () {
                        alert('error')
                    }
                })
            })
        })
    </script>

</body>
</html>

跨站请求伪造

一、简介

django为用户实现防止跨站请求伪造的功能,通过中间件 django.middleware.csrf.CsrfViewMiddleware 来完成。而对于django中设置防跨站请求伪造功能有分为全局和局部。

全局:

  中间件 django.middleware.csrf.CsrfViewMiddleware

局部:

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

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

二、应用

1、普通表单

html中设置Token:
  {% csrf_token %}

 

posted on 2017-04-19 11:07  周小百  阅读(201)  评论(0)    收藏  举报