简体   繁体   中英

Django + Ajax + Facebook API 403 FORBIDDEN

I am trying to apply Facebook Login API in django project. I planned to use Facebook username and default password(as far as django doesn't allow to create users without pass) and authenticate via ajax.

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

What I get in log is :

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

And in alert message:

POST /authfb/   403 FORBIDDEN
undefined

I am using django-ajax with decorator, but it works for me in all other parts of code.

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

In similar questions csrf security is often pointed as issue. So I tried this js code, which might be right, but still didn't help:

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

EDIT:

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

Try this instead of yours.

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

Also

ajaxPost('/authfb/', {'username': response.name, 'csrfmiddlewaretoken': getCookie('csrftoken')}, function(){ });

Update

Add

{% csrf_token %}

somewhere inside body of facebook.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM