python CSRF跨站请求伪造
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 </head>
7 <body>
8 <form method="POST" action="/csrf1.html/">
9 {% csrf_token %}
10 <input type="text" name="user">
11 <input type="submit" value="提交"/>
12 </form>
13 </body>
14 </html>
1 """day73 URL Configuration
2
3 The `urlpatterns` list routes URLs to views. For more information please see:
4 https://docs.djangoproject.com/en/1.10/topics/http/urls/
5 Examples:
6 Function views
7 1. Add an import: from my_app import views
8 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
9 Class-based views
10 1. Add an import: from other_app.views import Home
11 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
12 Including another URLconf
13 1. Import the include() function: from django.conf.urls import url, include
14 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
15 """
16 from django.conf.urls import url
17 from django.contrib import admin
18
19 from app01 import views
20
21
22 urlpatterns = [
23
24 url(r'^csrf1',views.csrf1),
25 ]
1 """
2 Django settings for day73 project.
3
4 Generated by 'django-admin startproject' using Django 1.10.6.
5
6 For more information on this file, see
7 https://docs.djangoproject.com/en/1.10/topics/settings/
8
9 For the full list of settings and their values, see
10 https://docs.djangoproject.com/en/1.10/ref/settings/
11 """
12
13 import os
14
15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
18
19 # Quick-start development settings - unsuitable for production
20 # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
21
22 # SECURITY WARNING: keep the secret key used in production secret!
23 SECRET_KEY = 'ct2d2^2k(l&%n@96xsd9y#0@!^_5a^peanb69ndouz&gx6%n3o'
24
25 # SECURITY WARNING: don't run with debug turned on in production!
26 DEBUG = True
27
28 ALLOWED_HOSTS = []
29
30
31 # Application definition
32
33 INSTALLED_APPS = [
34 'django.contrib.admin',
35 'django.contrib.auth',
36 'django.contrib.contenttypes',
37 'django.contrib.sessions',
38 'django.contrib.messages',
39 'django.contrib.staticfiles',
40 'app01.apps.App01Config',
41 ]
42
43 # csef设置地方如下:
44
45 MIDDLEWARE = [
46 'django.middleware.security.SecurityMiddleware',
47 'django.contrib.sessions.middleware.SessionMiddleware',
48 'django.middleware.common.CommonMiddleware',
49 #'django.middleware.csrf.CsrfViewMiddleware',
50 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 'django.contrib.messages.middleware.MessageMiddleware',
52 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53 ]
54
55
56
57
58 ROOT_URLCONF = 'day73.urls'
59
60 TEMPLATES = [
61 {
62 'BACKEND': 'django.template.backends.django.DjangoTemplates',
63 'DIRS': [os.path.join(BASE_DIR,'templates')]
64 ,
65 'APP_DIRS': True,
66 'OPTIONS': {
67 'context_processors': [
68 'django.template.context_processors.debug',
69 'django.template.context_processors.request',
70 'django.contrib.auth.context_processors.auth',
71 'django.contrib.messages.context_processors.messages',
72 ],
73 },
74 },
75 ]
76
77 WSGI_APPLICATION = 'day73.wsgi.application'
78
79
80 # Database
81 # https://docs.djangoproject.com/en/1.10/ref/settings/#databases
82
83 # DATABASES = {
84 # 'default': {
85 # 'ENGINE': 'django.db.backends.sqlite3',
86 # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
87 # }
88 # }
89
90 DATABASES = {
91 'default': {
92 'ENGINE': 'django.db.backends.mysql',
93 'NAME': 'ff3',
94 'USER': 'root',
95 'PASSWORD': '',
96 'HOST': 'localhost',
97 'PORT': 3306,
98 }
99 }
100
101
102
103
104 # Password validation
105 # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
106
107 AUTH_PASSWORD_VALIDATORS = [
108 {
109 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
110 },
111 {
112 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
113 },
114 {
115 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
116 },
117 {
118 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
119 },
120 ]
121
122
123 # Internationalization
124 # https://docs.djangoproject.com/en/1.10/topics/i18n/
125
126 LANGUAGE_CODE = 'en-us'
127
128 TIME_ZONE = 'UTC'
129
130 USE_I18N = True
131
132 USE_L10N = True
133
134 USE_TZ = True
135
136
137 # Static files (CSS, JavaScript, Images)
138 # https://docs.djangoproject.com/en/1.10/howto/static-files/
139
140 STATIC_URL = '/static/'
141 STATICFILES_DIRS =(
142 os.path.join(BASE_DIR,'static'),
143 )
注:在django中,如果setting里面# 'django.middleware.csrf.CsrfViewMiddleware',被注释,则没有csrf限制,
否则有csrf限制。
如果有csrf有限制或无限制,应用时2则有以下解决方案:
|
1
2
3
4
5
6
7
8
9
|
<br>#******************基本应用**********************# a.(HTML表单中form表单添加) # { % csrf_token %}# def csrf1(request):# if request.method == 'GET':# return render(request,'csrf1.html')# else:# return HttpResponse('哥们干啥来了')# *********************************************** |
|
1
2
3
4
|
#******************全站禁用***********************# b.(settings设置里面)# 'django.middleware.csrf.CsrfViewMiddleware',#************************************************ |
|
1
2
3
4
5
6
7
8
9
10
11
|
#******************局部禁用***********************# c.(全站使用前提下可以使用局部禁用)# 'django.middleware.csrf.CsrfViewMiddleware',# from django.views.decorators.csrf import csrf_exempt# @csrf_exempt# def csrf1(request):# if request.method == 'GET':# return render(request, 'csrf1.html')# else:# return HttpResponse('ok')# ************************************************ |
|
1
2
3
4
5
6
7
8
9
10
11
|
# ****************局部使用*************************# d.(全站禁用前提下可以使用局部使用)# 'django.middleware.csrf.CsrfViewMiddleware',# from django.views.decorators.csrf import csrf_protect# @csrf_protect# def csrf1(request):# if request.method == 'GET':# return render(request, 'csrf1.html')# else:# return HttpResponse('ok')# ************************************************ |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
#****************CBV中添加装饰器********************# c.特殊CBV# from django.views import View# from django.utils.decorators import method_decorator# @method_decorator(csrf_protect, name='dispatch')# class Foo(View):# def get(self, request):# pass## def post(self, request):# pass # def wrapper(func):# def inner(*args,**kwargs):# return func(*args,**kwargs)# return inner # 1. 指定方法上添加装饰器 # class Foo(View): # @method_decorator(wrapper) # def get(self,request): # pass # def post(self,request): # pass# 2. 在类上添加 # @method_decorator(wrapper,name='dispatch') #全部类添加 # @method_decorator(wrapper, name='get') # 只给get添加 # @method_decorator(wrapper, name='post') # 只给post添加 # class Foo(View): # def dispatch(self,request,*args,**kwargs) # pass # def get(self,request): # pass # def post(self,request): # pass#************************************************ |
二.Django之CSRF(Ajax)请求
|
1
2
3
4
5
|
def csrf1(request): if request.method == 'GET': return render(request,'csrf1.html') else: return HttpResponse('哥们干啥来了') |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
views.py<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <form method="POST" action="/csrf1.html/"> {% csrf_token %} <input type="text" name="user"> <input type="submit" value="提交"/> <a onclick="submitForm();">Ajax提交</a> </form><script src="/static/jquery-3.2.1.js"></script><script src="/static/jquery.cookie.js"></script><script> 第一种方式: function submitForm() { var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var user = $('#user').val(); $.ajax({ url:'/csrf1.html', type:'POST', data:{"user":user,'csrfmiddlewaretoken':csrf}, success:function (arg) { console.log(arg); } }) } 第二种方式:{# 获取Console值:在浏览器Console上输入document.cookie#} function submitForm() { var token = $.cookie('csrftoken'); var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var user = $('#user').val(); $.ajax({ url:'/csrf1.html', type:'POST', headers:{'X-CSRFToken':token}, data:{"user":user}, success:function (arg) { console.log(arg); } }) } </script></body></html> |

浙公网安备 33010602011771号