2016-02-28 97 views
0

我在django中有一个后端,而终端(rest框架)登录。Cordova和Django登录,会话过期

简单的Ajax

$.ajax({ 
     type : "POST", 
     url : url+login/", 
     data : {username:username, password:password} 
    }) 

和简单的查看

@api_view(['POST']) 
def login(request): 
    username = request.POST.get('username') 
    password = request.POST.get('password') 
    user = auth.authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      auth.login(request, user) 
      #When I type here: print request.session.items() 
      #I get _auth_user... things. 
     else: 
      pass 
    return Response({}) 

但是,当我在我的本机应用程序更改网页,而且调用另一个AJAX例如网址 “测试/”,而这个URL调用这个观点:

def test(request): 
    if request.user.is_authenticated(): 
     print "Logged in 
    else: 
     #redirect to home... 
    return response 

然后request.user.is_authenticated返回False,貌似会话过期是小的,所以我试试这个:

... 
auth.login(request, user) 
#When I type here: print request.session.items() 
#I get _auth_user... things. 
request.session.set_expire(0) 
... 

但这不起作用。编辑** 我使用Django Rest Framework。和“打开”:

REST_FRAMEWORK = { 
    'DEFAULT_AUTHENTICATION_CLASSES': (
     'rest_framework.authentication.BasicAuthentication', 
     'rest_framework.authentication.SessionAuthentication', 
    ) 
} 
+0

您没有告诉我们您的休息框架使用了什么。你能确认是否是Django-rest-framework? – dkarchmer

+0

是的,Django-rest-framework – Jeroj82

回答

0

我想你应该考虑使用

'rest_framework.authentication.TokenAuthentication' 

这将是更容易处理的移动应用程序,你可以只存储登录后的令牌,并使用该令牌用于其他任何API调用。它还允许您安全地使用csrf_exempt

AFAIK,$ .ajax不会发送任何cookie,如果您正在通过移动应用定义您正在做的域。所以,我认为你的问题与CORS有关,以及你如何初始化ajax调用。

尝试使用:

xhrFields: { withCredentials:true } 

您阿贾克斯电话。

您还需要建立CORS(使用Django-CORS-头)

为您可能需要担心其他的事情见http://www.django-rest-framework.org/topics/ajax-csrf-cors/。特别是

https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

但正如我所说,考虑使用令牌,而不是会议。

+0

好的,谢谢。你知道在django-rest + cordova中描述这种令牌机制的好文章吗? – Jeroj82

+0

我使用Ionic/Angular,但概念相对简单。我在你关于登录的其他问题上发布的代码显示了如何返回令牌。所以,在移动端需要的只是将该令牌存储在本地存储中(并在用户注销时删除)。然后在您的标头上使用{'授权':'标记'} – dkarchmer

+0

http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication – dkarchmer

0

我曾经在Django和post变量之前遇到过麻烦。 尝试将您的$ .ajax调用更改为:

$.ajax({ 
    type : "POST", 
    url : "yourURL/", 
    contentType: "application/x-www-form-urlencoded", 
    data : 'username='+encodeURIComponent(username)+'&password='+encodeURIComponent(password), 
});