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,这些将不会被浏览器拦截。这样,您就不必担心会将用户登录出去,因为身份验证直接与使用令牌进行的请求绑定。