[英]How to protect Django's views functions from directly calling through browser url
我想保護我的函數免於直接通過瀏覽器URL調用。 通過CSRF可能是可能的。 但是我做不到。 在前端,我正在使用ajax調用此函數。 因此,只能通過ajax進行調用,而不能直接通過瀏覽器url進行調用。
我的JavaScript代碼是
function getData(table,id){
data = []
$.ajax({
type: "POST",
url: "getData",
dataType:'json',
data:{'tableName':table},
success: function(result) {
for(var i=0;i<result.length;i++){
for (var key in result[i]){
val = result[i][key]
if (data.indexOf(val)==-1){
data.push(val)
}
}
}
$( "#"+id ).autocomplete({
source: data
});
}
});
}
所以我在javascript中調用此函數。
在urls.py中
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^getData', views.getData, name='getData'),
]
在Views.py中
def getData(request):
tableName = request.POST.get('tableName')
tableName = 'colleges'
cursor = connection.cursor()
query = "select * from "+tableName
cursor.execute(query)
columnDesc = cursor.description
result=[dict(zip([col[0] for col in columnDesc], row))
for row in cursor.fetchall()]
return HttpResponse(json.dumps(result), content_type="application/json")
因此,當我通過Web瀏覽器url直接調用時,就像...
http://localhost/shikshapp/getData
我從自己的觀點中得到了回應,並且能夠看到數據。
所以,我該如何保護這種呼叫..當令牌不存在時...但是該呼叫應該可以通過ajax訪問
如果您只想接受POST請求,則可以將require_http_methods裝飾器添加到視圖中,如下所示:
@require_http_methods(["POST"])
def getData(request):
tableName = request.POST.get('tableName')
tableName = 'colleges'
# ...
但是,如果您需要一些安全性並防止自己遭受CSRF攻擊,則需要添加CSRF令牌 :
# On the main view (the one that contains JS), add this decorator
@ensure_csrf_cookie
def yourView(request):
pass
# ...
# On the ajax view, refuse all requests without any csrf_token
@require_http_methods(["POST"])
@csrf_protect
def getData(request):
tableName = request.POST.get('tableName')
tableName = 'colleges'
# ...
然后,您的JS代碼必須如下所示:
// function to get token from cookie with jQuery
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;
}
// your function
function getData(table,id){
data = []
$.ajax({
type: "POST",
url: "getData",
dataType:'json',
data:{'tableName':table},
beforeSend: function(xhr, settings) {
// Add the CRSF header with the csrf cookie
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'););
}
success: function(result) {
for(var i=0;i<result.length;i++){
for (var key in result[i]){
val = result[i][key]
if (data.indexOf(val)==-1){
data.push(val)
}
}
}
$( "#"+id ).autocomplete({
source: data
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.