[英]Django + Ajax + Facebook API 403 FORBIDDEN
我正在嘗試在django項目中應用Facebook Login API。 我計划使用Facebook用戶名和默認密碼(只要django不允許不通過創建用戶),並通過ajax進行身份驗證。
FB.api('/me', function(response) {
alert(response.name); // it's fine, it's there
ajaxPost('/authfb/', {'username': response.name}, function(){ });
});
我在日志中得到的是:
Failed to load resource: the server responded with a status of 403 (FORBIDDEN)
並在警報消息中:
POST /authfb/ 403 FORBIDDEN
undefined
我正在將django-ajax與decorator一起使用,但是它在代碼的所有其他部分都對我有用。
views.py:
@ajax
def authfb(request):
if request.method == "POST":
username = request.POST.get('username')
password = '112358'
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
username = auth.get_user(request).username
print ('logged in succesfully')
return redirect("/user/%s/" % username)
else:
print("The username and password were incorrect.")
error_message_login_page = 'you do not exist'
return render(request, 'blog/facebook.html', {'error_message_login_page':error_message_login_page})
else:
print("whatever")
在類似的問題中,csrf安全性通常被認為是問題。 所以我嘗試了這個js代碼,這也許是正確的,但仍然沒有幫助:
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');
$.ajaxSetup({
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
編輯:
def fblogin(request):
if request.user.is_authenticated():
username = auth.get_user(request).username
return redirect("/user/%s/" % username)
print(username)
else:
return render(request, 'blog/facebook.html', {})`
試試這個代替你的。
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
也
ajaxPost('/authfb/', {'username': response.name, 'csrfmiddlewaretoken': getCookie('csrftoken')}, function(){ });
更新
加
{% csrf_token %}
在facebook.html
正文內部的某處
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.