XSS攻击
跨站脚本攻击 黑客在网页里边插入js代码,造成网页紊乱不安全。
不安全的表现:如果黑客在一个网页中插入拿到cookie的js代码,如果用户来访问这个网站,那么黑客就可以拿到用户的cookie信息,那么黑客就可以伪造用户的信息去了。
前端有个safe和后端mark_safe
使用safe要注意 如果用户能在页面上插入写js代码等等(修改代码),一定不要加safe如果实在要加,切记在后台做出过滤js代码等工作,如果是我们自己写的当然safe加上无妨
使用mark_safe时候,得到用户的数据时候也要对其进行处理
django默认给我们做了xss攻击这层防范
例子:模拟用户在输入框输入js代码带来的影响
在这里可以把csrf中间件在配置文件中注释掉
1 """djangoxss URL Configuration 2 3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/2.1/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: path('', 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: path('', Home.as_view(), name='home') 12 Including another URLconf 13 1. Import the include() function: from django.urls import include, path 14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 """ 16 from django.contrib import admin 17 from django.urls import path 18 from app01 import views 19 20 urlpatterns = [ 21 path('admin/', admin.site.urls), 22 path('index/', views.index), 23 path('comment/', views.comment), 24 path('test/', views.test), 25 ]
1 from django.shortcuts import render 2 3 msg = [] 4 5 6 def comment(request): 7 if request.method == 'GET': 8 return render(request, 'comment.html') 9 else: 10 m = request.POST.get('content') 11 if "script" in m: # 当然这是简单的判断js代码多了去了 12 return render(request, 'comment.html', {'error': '小逼崽子黑我'}) 13 else: 14 msg.append(m) 15 return render(request, 'comment.html') 16 17 18 def index(request): 19 return render(request, 'index.html', {'msg': msg}) 20 21 22 def test(request): 23 from django.utils.safestring import mark_safe 24 temp = "<a href='http://www.baidu.com'>baidu</a>" 25 newtemp = mark_safe(temp) 26 return render(request, 'test.html', {'temp': newtemp})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h3>评论信息</h3> {% for item in msg %} <div>{{ item | safe }}</div> {% endfor %} </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>comment</title> </head> <body> <form action="/comment/" method="post"> {% csrf_token %} <p><input type="text" name="content"></p> <input type="submit" value="提交"> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> </head> <body> {{ temp }} </body> </html>
扫描二维码关注公众号,回复:
6888044 查看本文章