Django + Ajax + Facebook API 403 FORBIDDEN

时间:2017-01-10 10:10:17

标签: javascript python ajax django facebook

我正在尝试在django项目中应用Facebook Login API。我计划使用Facebook用户名和默认密码(只要django不允许创建没有通过的用户)并通过ajax进行身份验证。

Failed to load resource: the server responded with a status of 403 (FORBIDDEN)

我在日志中得到的是:

POST /authfb/   403 FORBIDDEN
undefined

在警告信息中:

 @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")

我在装饰器中使用django-ajax,但它在代码的所有其他部分都适用于我。

views.py:

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") }
    });

在类似的问题中,csrf安全性经常被指出为问题。所以我尝试了这个js代码,这可能是正确的,但仍然没有帮助:

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', {})`

编辑:

-Duser.timezone="Asia/India"

1 个答案:

答案 0 :(得分:0)

试试这个而不是你的。

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

内部的某处