2014-01-16 30 views
0

現在我已經設置好了,當登錄成功登錄時,登錄div會消失,並且會出現一個註銷按鈕。我希望能夠擊中註銷並轉到我的註銷功能,只是重定向到原來的登錄頁面,但由於某種原因突然之後(只成功)的ajax表單提交,我得到了403錯誤:失敗的原因:CSRF令牌丟失或不正確。ajax頁面加載後沒有csrf令牌

想知道如果問題是我沒有正確傳遞CSRF令牌。我已經試過頁https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/#ajax

這裏的一切是我的代碼:

urls.py

from django.conf.urls import patterns, include, url 

from django.contrib import admin 
admin.autodiscover() 

urlpatterns = patterns('', 
    # Examples: 
    # url(r'^$', 'reportgenerator.views.home', name='home'), 
    # url(r'^blog/', include('blog.urls')), 

    url(r'^admin/', include(admin.site.urls)), 
    url(r'^login/', 'reportgenerator.views.login'), 
    url(r'^logout/', 'reportgenerator.views.logout'), 
) 

views.py

class LoginForm(forms.Form): 
username = forms.CharField(max_length=200) 
password = forms.CharField(max_length=200) 

def login(request): 
    c = {} 
    c.update(csrf(request)) 

    if request.POST: 
     form = LoginForm(request.POST) 
     if form.is_valid(): 
      user = auth.authenticate(username = form.cleaned_data['username'], 
       password = form.cleaned_data['password']) 
      is_success = False 
      if user is not None: 
       auth.login(request, user) 
       is_success = True 

      if request.is_ajax(): 
       if (is_success): 
        return render_to_response('login.html', c, context_instance = RequestContext(request)) 

      return render('was_failure') 
    else: 
     form = LoginForm() 

    c['form'] = form 
     return render(request, 'login.html', c) 

def logout(request): 
     auth.logout(request) 
     return HttpResponseRedirect('/login/') 

和我的javascript:

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'); 

function csrfSafeMethod(method) { 
    // these HTTP methods do not require CSRF protection 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
} 

function sameOrigin(url) { 
    // test that a given url is a same-origin URL 
    // url could be relative or scheme relative or absolute 
    var host = document.location.host; // host + port 
    var protocol = document.location.protocol; 
    var sr_origin = '//' + host; 
    var origin = protocol + sr_origin; 
    // Allow absolute or scheme relative URLs to same origin 
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || 
     (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || 
     // or any other URL that isn't scheme relative or absolute i.e relative. 
     !(/^(\/\/|http:|https:).*/.test(url)); 
} 

$.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
     if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { 
      // Send the token to same-origin, relative URLs only. 
      // Send the token only if the method warrants CSRF protection 
      // Using the CSRFToken value acquired earlier 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
    } 
}); 

jQuery(function() { 
    var form1 = jQuery("#contactform"); 

    form1.submit(function(e) { 
    $.ajax({ 
     type: "POST", 
     url: form1.attr('action'), 
     data: form1.serializeArray(), 
     success: function() { 
      popup.setAttribute("style","display: none;"); 
      blurback.setAttribute("style", "-webkit-filter: blur(0px)"); 
      $("#welcome").fadeIn("slow"); 
      $("#logoutfade").fadeIn("slow"); 
     }, 
     error: function() { 
      document.getElementById("password").value = ""; 
     } 
    }); 
     e.preventDefault(); 
    }); 
}); 

回答

0

要在此跟進 - 幾天後我想出了。我遇到這個問題的原因是因爲註銷按鈕出現在ajax登錄之前。當用戶通過身份驗證時,crsf令牌被重新生成,並且註銷按鈕頁面將舊的令牌附加到它上面,因爲它以前是生成的。我把它切換到在ajax調用之後生成登錄按鈕,並且一切都很好。

1

Dja非政府組織提供了有關如何執行Ajax請求,要求CSRF漂亮的詳細信息: https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/

使用jQuery沒有jQuery的cookie的插件:

// using jQuery 
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'); 

使用jQuery使用jQuery的Cookie插件:

var csrftoken = $.cookie('csrftoken'); 

而且那麼:

function csrfSafeMethod(method) { 
    // these HTTP methods do not require CSRF protection 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
} 
function sameOrigin(url) { 
    // test that a given url is a same-origin URL 
    // url could be relative or scheme relative or absolute 
    var host = document.location.host; // host + port 
    var protocol = document.location.protocol; 
    var sr_origin = '//' + host; 
    var origin = protocol + sr_origin; 
    // Allow absolute or scheme relative URLs to same origin 
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || 
     (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || 
     // or any other URL that isn't scheme relative or absolute i.e relative. 
     !(/^(\/\/|http:|https:).*/.test(url)); 
} 
$.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
     if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { 
      // Send the token to same-origin, relative URLs only. 
      // Send the token only if the method warrants CSRF protection 
      // Using the CSRFToken value acquired earlier 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
    } 
}); 

編輯(你的答案) 一個更普遍的做法: 首先確保已啓用了中間件:

'django.middleware.csrf.CsrfViewMiddleware', 

然後在您的JS文件:

$(document).on('click', '.some-class', function(){ 
    var $csrftoken = $.cookie('csrftoken'); 
    $.ajax({ 
     type: 'POST', 
     url: /your/url/, 
     crossDomain: false, 
     beforeSend: function(xhr) { 
      xhr.setRequestHeader("X-CSRFToken", $csrftoken); 
     }, 
     success: function(ctx) { 
      console.log(Success!) 
     } 
    }); 
}); 
+0

嘿是的我一直在盯着這個文檔,試圖實現它,但它不是真的有幫助。我如何在我的代碼中完全傳遞它? –

+0

檢查答案中的其他代碼,它應該工作:) – petkostas

+0

不,我不能得到它的工作。我沒有任何問題提交我的第一個Ajax表單,這很好,然後我的成功功能正常運行。然後,當我點擊註銷按鈕並嘗試重定向到/註銷/那是我遇到問題時。事實上,一切工作,除非我獲得成功的回報,然後我有csrf問題。 –