本文介绍: csrf校验是一种用于防止跨站请求伪造(Cross-Site Request Forgery)攻击安全措施。

目录

一、csrf跨站请求伪造详解        

二、csrf跨域请求伪造

【1】正常服务端

【2】钓鱼服务端

三、csrf校验

【介绍】

form表单中进行csrf校验:

【1】form表单如何校验

【2】ajax如何校验

四、csrf相关装饰器

【1】csrf_protect装饰器:

【2】csrf_exempt装饰器:

【3】FBV中使用上述装饰器

【4】CBV中使用上述装饰器

(1)  csrf_protect

(2)  csrf_exempt方法


一、csrf跨站请求伪造详解        

二、csrf跨域请求伪造

【1】正常服务端

<h1&gt;这是正规的网站</h1&gt;

<form action="" method="post"&gt;
    <p&gt;当前账户 :&gt;&gt;>> <input type="text" name="start_user"></p>
    <p>目标账户 :>>>> <input type="text" name="end_user"></p>
    <p>转账金额 :>>>> <input type="text" name="money"></p>
    <input type="submit">
</form>
  • 后端 
def transform_normal(request):
    if request.method == "POST":
        user_start = request.POST.get("start_user")
        user_end = request.POST.get("end_user")
        money = request.POST.get("money")
        return HttpResponse(f"当前账户 :>>> {user_start} 向目标用户 :>>> {user_end} 转账了 :>>> {money}")
    return render(request, 'transform_normal.html')

 【2】钓鱼服务端

<h1>这是钓鱼的网站</h1>

<form action="http://127.0.0.1:8000/transform_normal/" method="post">
    <p>当前账户 :>>>> <input type="text" name="start_user" ></p>
    <p>目标账户 :>>>> <input type="text"></p>
    <p><input type="text" name="end_user" value="Hopes" style="display: none"></p>
    <p>转账金额 :>>>> <input type="text" name="money"></p>
    <input type="submit">
</form>
  • 后端
def transform_normal(request):
    if request.method == "POST":
        user_start = request.POST.get("start_user")
        user_end = request.POST.get("end_user")
        money = request.POST.get("money")
        return HttpResponse(f"当前账户 :>>> {user_start} 向目标用户 :>>> {user_end} 转账了 :>>> {money}")
    return render(request, 'transform_normal.html')

三、csrf校验

介绍

form表单中进行csrf校验:

添加CSRF Token字段

设置Cookie

双重Cookie校验:

【1】form表单如何校验

{% csrf_token %}
<form action="" method="post">
    <p>username:<input type="text" name="username"></p>
    <p>transfer_user<input type="password" name="password"></p>
    <p>money<input type="text" name="money"></p>
    <input type="submit">
</form>
<input type="hidden" name="csrfmiddlewaretoken" value="zQaNPZsy1tVmLdqC7GIDOOOfR7yT9YfO58lJ5yrjZfTw2edZTrVYUllOVMnkwXKe">

【2】ajax如何校验

<button id="b1">ajax请求提交</button>
 
<script>
    $("#b1").click(function () {
        $.ajax({
            url: '',
            type: 'post',
            // (1) 利用标签查找获取页面上的随机字符串
            data: {"username": "dream","csrfmiddlewaretoken":$('[csrfmiddlewaretoken]').val()},
            success: function () {
 
            }
        })
    })
</script>
<button id="b1">ajax请求提交</button>
 
<script>
    $("#b1").click(function () {
        $.ajax({
            url: '',
            type: 'post',
            // (2) 利用模板语法提供的快捷书写
            data: {"username": "dream", "csrfmiddlewaretoken": "{{ csrf_token }}"},
            success: function () {
 
            }
        })
    })
</script>
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie &amp;&amp; document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
 
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) &amp;&amp; !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});
<button id="b1">ajax请求提交</button>
 
<script>
    $("#b1").click(function () {
        $.ajax({
            url: '',
            type: 'post',
            // (3) 定义外部js文件引入本地
            data: {"username": "dream"},
            success: function () {
 
            }
        })
    })
</script>

四、csrf相关装饰

  1. 网站整体部分校验csrf,部分不校验csrf
  2. 网站整体全部校验csrf,部分不校验csrf

【1】csrf_protect装饰器:

【2】csrf_exempt装饰器:

【3】FBV中使用上述装饰器

from django.views.decorators.csrf import csrf_protect, csrf_exempt
'''
csrf_protect  需要校验
csrf_exempt   忽视校验
'''

【4】CBV中使用上述装饰器

from django.views.decorators.csrf import csrf_protect, csrf_exempt
'''
csrf_protect  需要校验
	针对 csrf_protect 符合之前的装饰器的三种用法
csrf_exempt   忽视校验
	针对 csrf_exempt 只能给 dispatch 方法加才有效
'''

(1)  csrf_protect

from django.views import View
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils.decorators import method_decorator
 
 
class MyCsrf(View):
    def get(self, request):
        return HttpResponse("get")
    
    @method_decorator(csrf_protect)
    def post(self, request):
        return HttpResponse("post")
from django.views import View
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils.decorators import method_decorator
 
 
@method_decorator(csrf_protect)
class MyCsrf(View):
    def get(self, request):
        return HttpResponse("get")
    
    def post(self, request):
        return HttpResponse("post")
from django.views import View
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils.decorators import method_decorator
 
 
class MyCsrf(View):
    @method_decorator(csrf_protect)
    def dispatch(self, request, *args, **kwargs):
        return super(MyCsrf, self).dispatch(request, *args, **kwargs)
 
    def get(self, request):
        return HttpResponse("get")
 
    
    def post(self, request):
        return HttpResponse("post")

(2)  csrf_exempt方法

from django.views import View
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils.decorators import method_decorator
 
 
class MyCsrf(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(MyCsrf, self).dispatch(request, *args, **kwargs)
 
    def get(self, request):
        return HttpResponse("get")
 
    
    def post(self, request):
        return HttpResponse("post")

原文地址:https://blog.csdn.net/qq_53842456/article/details/134606112

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_18365.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注