You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django登录页面记住我功能故障:Cookie过期后登录失效求助

Django“记住我”Cookie过期后登录失效问题排查与修复

我用Django开发带“记住我”功能和会话管理的登录页面时发现:当给保存密码的Cookie设置过期时间后,登录功能会异常;但不设置过期时间时功能能正常运行。以下是我的views.py代码:

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from accounts.models import userData
from django.contrib import messages
from django.db import connection

# Create your views here.
def signUp(request):
    if request.method == 'POST':
        if request.POST.get('username') and request.POST.get('passwd'):
            saverecord = userData()
            saverecord.username = request.POST['username']
            saverecord.passwd = request.POST['passwd']
            saverecord.save()
            messages.success(request, 'User Created......!')
            return redirect('signIn')
    else:
        return render(request, 'SignUp.html')


def signIn(request):
    if request.COOKIES.get('cid'):
        return render(request, 'signIn.html', {'cookie1': request.COOKIES['cid'],'cookie2': request.COOKIES['cid2']})

    # if request.COOKIES.get('cid'):
    #     return render(request, 'signIn.html', {'cookie1': request.COOKIES['cid']})
    # if request.COOKIES.get('cid2'):
    #     return render(request, 'signIn.html', {'cookie2': request.COOKIES['cid2']})

    if request.method == 'POST':
        if userData.objects.filter(username=request.POST.get('username'), passwd=request.POST.get('passwd')):

            request.session['uid'] = request.POST.get('username')
            # messages.success(request, "Login Successful...")

            if request.POST.get("chk"):
                response = HttpResponse("User Credentials")
                response.set_cookie('cid', request.POST['username'])
                response.set_cookie('cid2', request.POST['passwd'])
                # response.set_cookie('cid2', request.POST['passwd'], max_age=180)
                return response
            return redirect('index')

        else:
            messages.success(request, "Invalid User....")
            return render(request, 'SignIn.html')
    else:
        return render(request, 'SignIn.html')



def index(request):
    if request.session.has_key('uid'):
        return render(request, 'index.html')
    else:
        return redirect('signIn')

def signOut(request):
    del request.session['uid']
    return render(request, 'signIn.html')

核心问题分析

  1. Cookie过期后的逻辑漏洞:signIn视图开头仅检查cid是否存在,就尝试将cid2(密码Cookie)传给模板。当cid2过期失效后,模板渲染会因找不到该Cookie值报错,导致登录流程异常。
  2. 登录成功后的响应错误:勾选“记住我”时返回HttpResponse("User Credentials")纯文本响应,而非重定向到首页,既破坏用户体验,也可能导致Cookie设置后会话跳转逻辑混乱。
  3. 严重安全隐患:直接将明文密码存储到Cookie中,Cookie在客户端可被轻易窃取,存在密码泄露风险;同时userData模型存储明文密码也是高危行为。

修复方案

1. 修复Cookie过期逻辑

修改signIn视图开头的Cookie检查逻辑,确保仅在两个Cookie都存在时才传递给模板:

def signIn(request):
    cookie_data = {}
    # 仅当cid和cid2同时存在时才传递给模板
    if request.COOKIES.get('cid') and request.COOKIES.get('cid2'):
        cookie_data['cookie1'] = request.COOKIES['cid']
        cookie_data['cookie2'] = request.COOKIES['cid2']
    
    # 后续POST请求逻辑...
    else:
        return render(request, 'SignIn.html', cookie_data)

2. 修正登录成功后的响应

勾选“记住我”时,改为重定向到首页并设置Cookie过期时间:

if request.POST.get("chk"):
    response = redirect('index')
    # 设置Cookie过期时间为7天(单位:秒)
    response.set_cookie('cid', request.POST['username'], max_age=60*60*24*7)
    # 强烈建议移除明文密码存储,若需自动填充仅保留用户名即可
    # response.set_cookie('cid2', request.POST['passwd'], max_age=60*60*24*7)
    return response

3. 修复安全问题

  • 立即停止在Cookie中存储明文密码,若需“记住我”自动填充,仅保留用户名Cookie即可;
  • 使用Django自带的make_password()和check_password()对用户密码进行加密存储与验证,替换当前明文存储逻辑:
# 注册时加密密码
from django.contrib.auth.hashers import make_password
saverecord.passwd = make_password(request.POST['passwd'])

# 登录时验证密码
from django.contrib.auth.hashers import check_password
user = userData.objects.filter(username=username).first()
if user and check_password(request.POST['passwd'], user.passwd):
    # 登录逻辑...

4. 优化登出逻辑

登出时同时清除“记住我”的Cookie:

def signOut(request):
    request.session.pop('uid', None)
    response = render(request, 'signIn.html')
    response.delete_cookie('cid')
    response.delete_cookie('cid2')
    return response

内容的提问来源于stack exchange,提问作者shivendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:15:50