解析session与cookie

Session和Cookie相关概念

  • Session和Cookie都是有服务器生成的。
  • Session和Cookie都是键值对形式保存,主要用于存储特定的一些状态值。
  • Session保存在服务器,Cookie保存在客户端。通常来说,Session的ID会以Cookie的形式返回给客户端的。
  • Session和Cookie都是有生命周期的。Cookie的生命周期受到Cookie自身的有效期和客户端的影响,一般来说,浏览器(客户端)是会自动将存活的Cookie封装在请求头里面,向服务器发送。如果Cookie有效期过期或客户端清理了Cookie,则发送的请求中就没有Cookie值;Session的生命周期受到Session自身的有效期和客户端是否关闭的影响。SessionID虽然是已Cookie的形式返回给客户端,但是它是不受客户的Cookie容器的管理,而是和客户端进程有关,即客户端进程不关闭,一般Session在客户端就不会失效。
  • Session和Cookie都是有作用域的。

实例演示:以cookie记录用户状态

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录Session与Cookie</title>
    <link rel="stylesheet"
          href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    {% if username %}
        <h2>欢迎您 :{{ username }}</h2>
        <a href="/logout/">注销</a>
    {% else %}
        <form action="/login_cookie/" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label class="sr-only">username</label>
                <input type="text" class="form-control" name="username"
                       placeholder="用户名"/>
            </div>
            <div class="form-group">
                <label class="sr-only">Password</label>
                <input type="password" class="form-control" name="passwd"
                       placeholder="密码"/>
            </div>
            <div class="form-group">
                <input class="btn btn-primary" type="submit" value="Submit">
            </div>
        </form>
    {% endif %}

</div>
<script type="application/javascript"
        src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="application/javascript"
        src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

login/views.py

from django.shortcuts import render


# Create your views here.

def login_cookie(request):
    # 从Cookie中获取用户名
    username = request.COOKIES.get("username", False)
    response = render(request, 'login.html', locals())
    # 如果POST表单,进行登录验证
    if request.method == "POST":
        username = request.POST['username']
        pwd = request.POST['passwd']
        if username == 'ptqa' and pwd == '4399':
            response = render(request, 'login.html', locals())
            # 设置Cookie
            response.set_cookie("username", username)
    return response

step1:首次访问http://127.0.0.1:8000/login_cookie/   可以观察到 Request headers 中没有Cookie,处于未登录状态

step2:登录后(输入账号名ptqa,密码4399)自动跳转首页,此时可以观察到,在Response Headers 中存在Set-Cookie:username=ptqa; Path=/

 step3:此时,刷新页面或新开窗口访问http://127.0.0.1:8000/login_cookie/ 可观察到请求中的Request Headers 中自动带上 Cookie:username=ptqa; 页面处于已登录状态。

显然,通过cookie的方式验证用户登录容易被破解,如下使用jmeter篡改Cookie值,则同样可以进入已登录状态显示界面,如下

实例演示:以Session记录用户状态

 login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录Session与Cookie</title>
    <link rel="stylesheet"
          href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    {% if username %}
        <h2>欢迎您 :{{ username }}</h2>
        <a href="/logout/">注销</a>
    {% else %}
        <form action="/login_session/" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label class="sr-only">username</label>
                <input type="text" class="form-control" name="username"
                       placeholder="用户名"/>
            </div>
            <div class="form-group">
                <label class="sr-only">Password</label>
                <input type="password" class="form-control" name="passwd"
                       placeholder="密码"/>
            </div>
            <div class="form-group">
                <input class="btn btn-primary" type="submit" value="Submit">
            </div>
        </form>
    {% endif %}

</div>
<script type="application/javascript"
        src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="application/javascript"
        src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

login/views.py

from django.shortcuts import render, redirect


# Create your views here.

def login_session(request):
    # 从Session中获取用户名
    username = request.session.get('username', False)
    # 如果POST表单,进行登录验证
    if request.method == "POST":
        username = request.POST['username']
        pwd = request.POST['passwd']
        if username == 'ptqa' and pwd == '4399':
            # 设置Session
            request.session['username'] = username
            # request.session.set_expiry(300) #会让 Session 在五分钟后过期

    # 登录不成功或第一访问就停留在登录页面
    return render(request, 'login.html', locals())


def logout(request):
    if "username" in request.session:
        del request.session['username']
    return redirect("/login_session/")

step1:首次访问http://127.0.0.1:8000/login_session/ 可观察到Request Headers 中并没有sessionId 并且处于未登录状态

step2:登录,输入账号ptqa,密码4399 ,在Response Headers 中可以观察到存在 Set-Cookie:sessionid=qigvbt2ckkcc5rydr46dehzjryg0mh41;

 step3:重新刷新页面或新开窗口,则观察到在Request Headers 中带有Cookie Sessionid,并且处于登录状态。

显然,这种使用sessonid的方式比较安全,如果篡改sessionid,则无法进行登录。如下:


***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***
原文地址:https://www.cnblogs.com/guanfuchang/p/7487045.html