Implement "Remember Me" Django

时间:2015-05-24 20:59:16

标签: python django authentication django-rest-framework jwt

I'm currently trying to implement "Remember Me" feature in Django.

I'm using both SessionAuthentication from Django REST framework and JSONWebTokenAuthentication from djangorestframework-jwt.

However, I don't know how to implement the concept of "Remember Me" for these two authentications. Like how do I extend the session forever and how do I extend the token forever (I'm using JWT auth for mobile & desktop - Session auth for browser).

Also, what is the secure way to implement this feature for both authentications?

2 个答案:

答案 0 :(得分:6)

我需要提前澄清一些事项:身份验证的工作原理以及SessionAuthenticationJSONWebTokenAuthentication的到期时间。

会话认证

Django REST框架提供的SessionAuthentication类实际上只是session framework provided by Django上的一小层。所以如果你能实现一个"记住我"使用他们的会话在Django中运行,DRF也将继承它。

幸运的是,有人已经在Stack Overflow上询问过这个问题:Django “Remember Me” with built-in login view and authentication form

基本上,它归结为将the SESSION_COOKIE_AGE setting(默认为2周)更改为非常高的数字。另外,请务必记住长期会话的含义,并且可能会检查您访问的网站默认会话Cookie的持续时间(通常为2周到6个月)。

JSON Web令牌

django-rest-framework-jwt提供的JSONWebToken身份验证类根据JSON Web令牌对请求进行身份验证。默认情况下,令牌将在五分钟后过期,但最多可刷新七天。

令牌到期时间由JWT_EXPIRATION_DELTA设置控制。建议不要将此时间过长,而应将use refresh tokens用于长期令牌。您可以使用JWT_ALLOW_REFRESH设置启用刷新令牌,并使用JWT_REFRESH_EXPIRATION_DELTA设置控制到期时间。

答案 1 :(得分:-1)

依赖项

from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate
from site_user.models import User

当我们进入登录页面时,此代码将从会话中撤消用户名和密码

def home(request):
    if request.session.has_key('username') and request.session.has_key('password'):
        username = request.session['username']
        password = request.session['password']
        context_dict = {'username': username, 'password': password}
        return render(request, 'sadmin/login.html', context=context_dict)
    else:
        context_dict = {'username': '', 'password': ''}
        return render(request, 'sadmin/login.html', context=context_dict)

以下代码用于用户身份验证。 HTML文件中的“ is_remember_check”复选框字段

@csrf_exempt
def login(request):
    if request.method == "POST":
        if request.POST['is_remember_check'] == 'true':
            request.session['username'] = request.POST['username']
            request.session['password'] = request.POST['password']

        user = authenticate(username=request.POST['username'], password=request.POST['password'])

        if user is not None:
            return JsonResponse({'result': request.POST, 'status': True})
        else:
            return JsonResponse({'result': request.POST, 'status': False})

从登录页面调用AJAX

function login(){
    remember_checkbox_value = document.getElementsByName('remember')[0].checked;
    username = document.getElementsByName('username')[0].value;
    password = document.getElementsByName('password')[0].value;
    var post_data = {username:username, password:password, is_remember_check:remember_checkbox_value};

    $.ajax({
                url: '/sadmin/login/',
                method: 'POST',
                data: post_data,
                dataType: 'json',
                success: function (response) {
                        if (response.status){
                        alert("User login is successful");
                        window.location.reload();
                        }
                        else{
                        alert("User login is not successful");
                        window.location.reload();
                        }
                }
        });
}

HTML代码

<div class="form-actions">
            <label class="checkbox">
            <input type="checkbox" name="remember"/> Remember me </label>
            <button type="button" class="btn green-haze pull-right" onclick="login()">Login <i class="m-icon-swapright m-icon-white"></i>
            </button>
        </div>