如何防范auth模块中的csrf跨站请求伪造攻击?

2026-05-25 04:411阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计972个文字,预计阅读时间需要4分钟。

如何防范auth模块中的csrf跨站请求伪造攻击?

CSRF跨站请求伪造有多种检测方式,Django仅提供了基本的表单验证。要实现前后端整合,可以使用模板语法中的表单元素。例如:

csrf跨站请求伪造

针对csrf相关的校验有很多种方式,django只是提供了一些而已

form表单

前提必须是前后端整合,能够使用模板语法

<form action="" method="post"> {% csrf_token %} <p>当前账户:<input type="text" name="current_user"></p> <p>目标账户:<input type="text" name="target_user"></p> <p>转账金额:<input type="text" name="money"></p> <input type="submit"> </form> ajax请求 方式1

页面任意位置先写{% csrf_token %} 之后获取数据

方式2

模板语法直接获取

js脚本自动处理

只能适用于ajax提交,form表单还是需要额外指定,直接cv拷贝

function getCookie(name) { var cookieValue = null; if (document.cookie && 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) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); csrf相关装饰器

csrf_exempt:忽略csrf校验;csrf_protect:开启csrf校验

from django.views.decorators.csrf import csrf_exempt,csrf_protect 针对FBV

# @csrf_exempt # @csrf_protect def login(request): return render(request, 'login.html') 针对CBV

from django import views from django.utils.decorators import method_decorator # @method_decorator(csrf_protect, name='post') # 可以校验 # @method_decorator(csrf_exempt, name='post') class MyView(views.View): # @method_decorator(csrf_protect) # 可以校验 def dispatch(self, request, *args, **kwargs): super(MyView, self).dispatch(request, *args, **kwargs) # @method_decorator(csrf_protect) # 可以校验 # @method_decorator(csrf_exempt) # 无效 def post(self, request): return HttpResponse('from MyView post')

csrf_protect:三种CBV添加装饰器的方式都可以

csrf_exempt:只有一种方式可以生效(重写的dispatch方法)

@method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(MyView, self).dispatch(request, *args, **kwargs) auth模块 概念

auth模块是django提供给你快速完成用户相关功能的模块

django也配套提供了一张'用户表':执行数据库迁移命令之后默认产生的auth_user

如何防范auth模块中的csrf跨站请求伪造攻击?

django自带的admin后台管理用户登录参考的就是auth_user表

创建admin后台管理员用户:createsuperuser

自动对用户密码进行加密处理并保存

模块方法

from django.contrib import auth

  • 验证用户名和密码是否正确

    auth.authenticate()

  • 保存用户登录状态

    auth.login()

def lg(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') is_user_obj = auth.authenticate(request, username=username, password=password) # res = auth.authenticate(request, username=username, password=password) # print(res) # 校验正确返回的是用户对象,错误返回的是None if is_user_obj: # 记录用户登录状态 auth.login(request, is_user_obj) return render(request, 'lg.html')

  • 获取当前用户对象

    request.user # session删除掉会返回匿名用户

  • 判断当前用户是否登录

    request.user.is_authenticated() # 返回布尔值

  • 校验登录装饰器

    from django.contrib.auth.decorators import login_required # 局部配置 @login_required(login_url='/lg/') # 全局配置 @login_required LOGIN_URL = '/lg/' # 需要在配置文件中添加配置

  • 修改密码

    if request.method == 'POST': old_password = request.POST.get('old_password') new_password = request.POST.get('new_password') # 先比对原密码是否正确 is_right = request.user.check_password(old_password) if is_right: # 修改密码 request.user.set_password(new_password) # 临时修改密码 # 保存数据 request.user.save() # 修改操作同步到数据库

  • 注销登录

    auth.logout(request)

  • 注册用户

    from django.contrib.auth.models import User def register(request): # User.objects.create(username='chen', password='111') # 不能使用create,密码不会加密 # User.objects.create_user(username='jame', password='111') User.objects.create_superuser(username='kurry', password='1111', email='111@qq.com') return HttpResponse('注册成功')

扩展表字段 方式1

编写一对一表关系(了解)

方式2

类继承(推荐)

from django.contrib.auth.models import AbstractUser class Users(AbstractUser): # 编写AbstractUser类中没有的字段 不能冲突!!! phone = models.BigIntegerField() addr = models.CharField(max_length=32)

配置文件

AUTH_USER_MODEL = 'app01.Users' 注意

类继承之后,需要重新执行数据库迁移命令,并且库里面是第一次操作才可以

auth模块所有的方法都可以直接在自定义模型类上面使用

自动切换参照表

本文共计972个文字,预计阅读时间需要4分钟。

如何防范auth模块中的csrf跨站请求伪造攻击?

CSRF跨站请求伪造有多种检测方式,Django仅提供了基本的表单验证。要实现前后端整合,可以使用模板语法中的表单元素。例如:

csrf跨站请求伪造

针对csrf相关的校验有很多种方式,django只是提供了一些而已

form表单

前提必须是前后端整合,能够使用模板语法

<form action="" method="post"> {% csrf_token %} <p>当前账户:<input type="text" name="current_user"></p> <p>目标账户:<input type="text" name="target_user"></p> <p>转账金额:<input type="text" name="money"></p> <input type="submit"> </form> ajax请求 方式1

页面任意位置先写{% csrf_token %} 之后获取数据

方式2

模板语法直接获取

js脚本自动处理

只能适用于ajax提交,form表单还是需要额外指定,直接cv拷贝

function getCookie(name) { var cookieValue = null; if (document.cookie && 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) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); csrf相关装饰器

csrf_exempt:忽略csrf校验;csrf_protect:开启csrf校验

from django.views.decorators.csrf import csrf_exempt,csrf_protect 针对FBV

# @csrf_exempt # @csrf_protect def login(request): return render(request, 'login.html') 针对CBV

from django import views from django.utils.decorators import method_decorator # @method_decorator(csrf_protect, name='post') # 可以校验 # @method_decorator(csrf_exempt, name='post') class MyView(views.View): # @method_decorator(csrf_protect) # 可以校验 def dispatch(self, request, *args, **kwargs): super(MyView, self).dispatch(request, *args, **kwargs) # @method_decorator(csrf_protect) # 可以校验 # @method_decorator(csrf_exempt) # 无效 def post(self, request): return HttpResponse('from MyView post')

csrf_protect:三种CBV添加装饰器的方式都可以

csrf_exempt:只有一种方式可以生效(重写的dispatch方法)

@method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(MyView, self).dispatch(request, *args, **kwargs) auth模块 概念

auth模块是django提供给你快速完成用户相关功能的模块

django也配套提供了一张'用户表':执行数据库迁移命令之后默认产生的auth_user

如何防范auth模块中的csrf跨站请求伪造攻击?

django自带的admin后台管理用户登录参考的就是auth_user表

创建admin后台管理员用户:createsuperuser

自动对用户密码进行加密处理并保存

模块方法

from django.contrib import auth

  • 验证用户名和密码是否正确

    auth.authenticate()

  • 保存用户登录状态

    auth.login()

def lg(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') is_user_obj = auth.authenticate(request, username=username, password=password) # res = auth.authenticate(request, username=username, password=password) # print(res) # 校验正确返回的是用户对象,错误返回的是None if is_user_obj: # 记录用户登录状态 auth.login(request, is_user_obj) return render(request, 'lg.html')

  • 获取当前用户对象

    request.user # session删除掉会返回匿名用户

  • 判断当前用户是否登录

    request.user.is_authenticated() # 返回布尔值

  • 校验登录装饰器

    from django.contrib.auth.decorators import login_required # 局部配置 @login_required(login_url='/lg/') # 全局配置 @login_required LOGIN_URL = '/lg/' # 需要在配置文件中添加配置

  • 修改密码

    if request.method == 'POST': old_password = request.POST.get('old_password') new_password = request.POST.get('new_password') # 先比对原密码是否正确 is_right = request.user.check_password(old_password) if is_right: # 修改密码 request.user.set_password(new_password) # 临时修改密码 # 保存数据 request.user.save() # 修改操作同步到数据库

  • 注销登录

    auth.logout(request)

  • 注册用户

    from django.contrib.auth.models import User def register(request): # User.objects.create(username='chen', password='111') # 不能使用create,密码不会加密 # User.objects.create_user(username='jame', password='111') User.objects.create_superuser(username='kurry', password='1111', email='111@qq.com') return HttpResponse('注册成功')

扩展表字段 方式1

编写一对一表关系(了解)

方式2

类继承(推荐)

from django.contrib.auth.models import AbstractUser class Users(AbstractUser): # 编写AbstractUser类中没有的字段 不能冲突!!! phone = models.BigIntegerField() addr = models.CharField(max_length=32)

配置文件

AUTH_USER_MODEL = 'app01.Users' 注意

类继承之后,需要重新执行数据库迁移命令,并且库里面是第一次操作才可以

auth模块所有的方法都可以直接在自定义模型类上面使用

自动切换参照表