Cordova和Django登录,会话到期

时间:2016-02-28 21:33:49

标签: python django cordova django-rest-framework

我在django中有一个后端,并且有一个端点(rest框架)可以登录。

简单的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“test /”,此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',
    )
}

2 个答案:

答案 0 :(得分:0)

我认为你应该考虑使用

'rest_framework.authentication.TokenAuthentication'

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

AFAIK,如果您跨越域名,$ .ajax将不会发送任何Cookie,您根据定义从移动应用程序进行操作。所以,我认为您的问题与CORS以及如何初始化ajax调用有关。

尝试使用:

xhrFields: { withCredentials:true }

在.ajax电话上。

您还需要设置CORS(使用django-cors-headers)

有关您可能需要担心的其他事项,请参阅http://www.django-rest-framework.org/topics/ajax-csrf-cors/。特别是

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

但正如我所说,考虑使用令牌代替会话。

答案 1 :(得分:0)

我之前遇到过Django和发布变量的麻烦。 尝试将$ .ajax调用更改为:

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