我已经读过csrfmiddlewaretoken和csrftoken cookie都必须是django POST请求成功的正确值(django: csrftoken COOKIE vs. csrfmiddlewaretoken HTML Form value)。对我来说就是这种情况,但我仍然得到403:
在Chrome控制台中:
document.cookie
返回
"csrftoken=Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD"
但是
$.get('https://learningdollars.fwd.wf/csrftoken/', function(data){
console.log(data)
token = $.parseHTML(data)[0].value
console.log(token)
$.ajax({
type: "POST",
url: 'https://learningdollars.fwd.wf/confirmemail/',
data: {email: 'gdasu@alumni.stanford.edu', csrfmiddlewaretoken: token},
contentType: "application/json"
})
.done(function(response) {
console.log('done!')
})
.fail(function(error) {
console.log('fail!')
})
})
返回
> Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
> <input type='hidden' name='csrfmiddlewaretoken' value='Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD' />
> Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD
> POST https://learningdollars.fwd.wf/confirmemail/ 403 (Forbidden)
> fail!
我有
'django.middleware.csrf.CsrfViewMiddleware',
在我的django中间件中激活。
我的根urls.py包含:
url(r'^csrftoken/$', views.get_csrf_token),
url(r'^confirmemail/$', views.confirm_email, name='confirm_email'),
而且,我的观点是:
def get_csrf_token(request):
c = {}
c.update(csrf(request))
print c
return render_to_response('csrf.html', c)
def confirm_email(request):
print 'here'
return JsonResponse({'response': 0})
顺便说一句,csrf.html的内容只是csrftoken(在输入标记内):
{% csrf_token %}
我做错了什么?
答案 0 :(得分:4)
好吧,我找到了解决方案。它只是将数据作为URI而不是json发送。 (顺便说一句,我尝试在上面指定dataType:'json'无济于事。)以下是在chrome控制台中:
> email = 'gdasu@alumni.stanford.edu'
< "gdasu@alumni.stanford.edu"
> csrftoken = 'L2MxD1XQIF1Xto5NkzUgGUYiHPyyz3K5'
< "L2MxD1XQIF1Xto5NkzUgGUYiHPyyz3K5"
> $.ajax({
type: "POST",
url: 'https://learningdollars.fwd.wf/confirmemail/',
data: "email="+ encodeURI(email) + "&csrfmiddlewaretoken=" + encodeURI(csrftoken),
success: function(data) { console.log(data); }
})
< Object {response: 1}
仍然不确定我在json方面做错了什么,但以下是我试过的:
$.ajax({
type: "POST",
url: "https://learningdollars.fwd.wf/confirmemail/",
data: JSON.stringify({ email: email, csrfmiddlewaretoken: csrftoken }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
答案 1 :(得分:-2)
您可以通过添加csrf_exempt禁止Django CSRF告诉视图不检查csrf令牌。
ng-style="{'width': '40%', 'border': 'none'}"