Django Ajax Facebook API 403 FORBIDDEN

2024-06-02 06:03:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

 FB.api('/me', function(response) {
     alert(response.name); // it's fine, it's there
     ajaxPost('/authfb/', {'username': response.name}, function(){ });
});

我在日志中看到的是:

^{pr2}$

在警报消息中:

POST /authfb/   403 FORBIDDEN
undefined

我在decorator中使用djangoajax,但它在代码的所有其他部分都适用。在

在视图.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', {})`

Tags: nameauthreturnifcookieresponserequestvar
1条回答
网友
1楼 · 发布于 2024-06-02 06:03:33

试试这个代替你的。在

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

还有

^{pr2}$

更新

添加

{% csrf_token %}

facebook.html主体内部的某个地方

相关问题 更多 >