如何在 django 中'protect' ajax 视图



我有各种 ajax 视图,它们接受来自 jquery 的数据并按如下方式工作:

@csrf_exempt
def update_view(request):
if request.method == 'POST':
process_data()

我的问题是,我怎样才能更好地保护这些观点?我是否应该在 ajax 请求中传递类似令牌的东西以验证它是否是有效的调用?否则,欺骗上述 ajax 视图似乎很容易。

选项 1:在使用 jquery 提交 AJAX 数据的 Django 模板中包含以下内容:

<script>
// This ensures that jQuery AJAX functions submit the CSRF token
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);
}
}
});
</script>

这样,您的视图中就不需要@csrf_exempt装饰器了。

来源 - https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

选项 2:确保模板中的表单具有{% csrf_token %}标记:

<form id="form_1" method="POST" action="{% url 'update-view' %}">
{% csrf_token %}
{{ form }}
<button type="submit">Save</button>
</form>

然后使用 jQuery 处理表单提交事件,并使用 serialise(( 函数对表单元素进行编码。

var thisForm = $( "#form_1" );
thisForm.submit(function( event ) {
event.preventDefault();
$.ajax({
url: thisForm.attr( "action" ),
type: thisForm.attr( "method" ),
data: thisForm.serialize()
})
.done(function( data ) {
alert( "Data Saved: " + data );
});
});

csrfmiddlewaretoken值将包含在您的表单数据中:

最新更新