0

用於登錄,我做的是這樣的:Django的REST API註銷請求

function setHeader(xhr) { 
     // as per HTTP authentication spec [2], credentials must be 
     // encoded in base64. Lets use window.btoa [3] 
     xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ':' + password)); 
    } 

    $.ajax({type: "POST", url: AUTH_URL, beforeSend: setHeader}). 
     fail(function(resp){ 
      console.log('bad credentials.') 
     }). 
     done(function(resp){ 
     }); 

之後,我存儲在本地存儲會話。

然而,對於註銷,我無法弄清楚如何使用這個會話與請求頭髮送,使Django的:request.logout()註銷用戶具有會話ID

回答

1

對於登錄即可添加視圖與此類似:

import json 
import requests 
from django.shortcuts import render_to_response 
from django.http import HttpResponseRedirect 

@csrf_protect 
def login(request): 
    if request.method == "POST": 
     login = requests.post('http://your_url/api-token-auth/', data={'username': request.POST['username'], 'password': request.POST['password']}) 
     response = json.loads(login.text) 
     if response.status_code == 200: 
      token = response['token'] 
      request.session.flush() 
      request.session['user'] = request.POST['username'] 

      if request.session.test_cookie_worked(): 
       request.session.delete_test_cookie() 

      return HttpResponseRedirect("/") 

     else: 
      error = "Error" 
    request.session.set_test_cookie() 
    return render_to_response("login.html", {"error": error}, RequestContext(request)) 

對於全部註銷你有你的觀點做的是:

def logout(request): 
    request.session.flush() 
    return HttpResponseRedirect('/') 

在您的API方面,你必須DEFI NE API-令牌身份驗證的網址:這裏是tutorial更多信息

url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token') 

這樣你會得到你的令牌與API通信。在TokenAuthentication旁邊,您可以定義和SessionAuthentication。更多關於您可以在上述教程中找到的內容

+0

我的request.session對象是空的。 我的疑問是 - 如何在客戶端形成請求對象,並將其發送到Django REST API – 2014-10-27 12:09:36

+0

將請求對象存儲在客戶端可能會很危險。有人可以劫持您的請求並將自己呈現爲您。 – Sasa 2014-10-27 12:14:21

+0

所以我應該以某種方式在服務器端存儲每個登錄用戶的請求對象? 如果是的話,你可以建議一種方法來做到這一點? – 2014-10-27 12:15:42

1

您正在使用HTTP Basic Authentication,它沒有定義將用戶註銷的方式。它不綁定到Django會話,所以你不能清除它。儘管瀏覽器可能會選擇發送原始憑據(未經測試),但您可能會從會話存儲清除令牌併發送無效令牌。

還有quitea fewquestions關於堆棧溢出。你最好的選擇看起來像是發送無效的證書,希望用戶的瀏覽器會使所有保存的證書無效。

您可能能夠使用基於令牌的身份驗證形式,如TokenAuthenticationOAuth,這些將不會被瀏覽器攔截。這樣,您就不必擔心會將用戶登錄出去,因爲身份驗證直接與使用令牌進行的請求綁定。