浏览器:理解HTTP无状态与Cookie的使用

简介: 浏览器:理解HTTP无状态与Cookie的使用

一、理解HTTP无状态

1.1、理解http无状态

http无状态是指协议对于用户身份、用户状态、用户权限、交互场景等没有记忆能力。简单讲就是不能识别用户。

1.2、http无状态的优点:

可以更快地处理大量的事务,确保协议的可伸缩性,减少服务器的 CPU 及内存资源的消耗。

1.3、因为http无状态所以引出本文内容Cookie。

1.4、Cookie往往存储Token等用来记录客户端用户信息,本文仅介绍Cookie相关。

二、理解Cookie:

2.1、Cookie 以名/值对形式存储,举例:

username=snowball

2.2、cookie 存储在客户端。cookie有大小限制,大小一般是4k,超过这个限制,cookie中无法存储该数据。

2.3、cookie数据是指某些网站为了辨别用户身份或实现业务能力,储存在用户本地终端上的数据(通常经过加密),由用户客户端计算机暂时或永久保存的信息。

2.4、截图

三、Cookie属性:

3.1、Name/Value:设置Cookie的名称及相对应的值。

3.2、Expires属性:设置Cookie的生存期。

有两种存储类型的Cookie:会话性与持久性。

Expires属性缺省时,为会话性Cookie,仅保存在客户端内存中,并在用户关闭浏览器时失效;

持久性Cookie会保存在用户的硬盘中,直至生存期到或用户直接在网页中单击“注销”等按钮结束会话时才会失效 。

3.3、Path属性:定义了Web站点上可以访问该Cookie的目录。

3.4、Domain属性:指定了可以访问该 Cookie 的 Web 站点或域。Cookie 机制并未遵循严格的同源策略,允许一个子域可以设置或获取其父域的 Cookie。当需要实现单点登录方案时,Cookie 的上述特性非常有用,然而也增加了 Cookie受攻击的危险,比如攻击者可以借此发动会话定置攻击。因而,浏览器禁止在Domain属性中设置.org、.com 等通用顶级域名、以及在国家及地区顶级域下注册的二级域名,以减小攻击发生的范围。

3.5、Secure属性:指定是否使用HTTPS安全协议发送Cookie。使用HTTPS安全协议,可以保护Cookie在浏览器和Web服务器间的传输过程中不被窃取和篡改。该方法也可用于Web站点的身份鉴别,即在HTTPS的连接建立阶段,浏览器会检查Web网站的SSL证书的有效性。但是基于兼容性的原因(比如有些网站使用自签署的证书)在检测到SSL证书无效时,浏览器并不会立即终止用户的连接请求,而是显示安全风险信息,用户仍可以选择继续访问该站点。由于许多用户缺乏安全意识,因而仍可能连接到Pharming攻击所伪造的网站。

3.6、HTTPOnly 属性 :用于防止客户端脚本通过document.cookie属性访问Cookie,有助于保护Cookie不被跨站脚本攻击窃取或篡改。但是,HTTPOnly的应用仍存在局限性,一些浏览器可以阻止客户端脚本对Cookie的读操作,但允许写操作;此外大多数浏览器仍允许通过XMLHTTP对象读取HTTP响应中的Set-Cookie头。

四、cookie基础用法:

4.1、创建cookie

document.cookie = "username=snowball"

4.2、读取cookie

document.cookie

注意:设置了 HttpOnly 标志的 Cookie 无法访问

4.3、修改cookie

document.cookie = "username=snowwin"

4.4、删除cookie

document.cookie = "username="

4.5、创建方法,设置cookie

function setCookie(cname,cvalue,exdays)
{
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
  var expires = "expires="+d.toGMTString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

4.6、使用方法,获取cookie

function getCookie(cname)
{
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) 
  {
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

4.7、设置secure字段

标记为 secure 的 Cookie 只应通过被 Https 协议加密过的请求发送给服务端。(通过 https 创建的 Cookie 只能通过 Https 请求将 Cookie 携带到服务器,通过 http 无法拿到 Cookie)

document.cookie = 'testname=snowball;Secure=true'

五、过程记录

5.1、根据同源策略,cookie是区分端口的。

但是浏览器实现来说,“cookie区分域,而不区分端口。

也就是说,同一个ip下的多个端口下的cookie是共享的!

也就是本地开发及服务端部署后同域下cookie是没有跨域问题的!

也就是根据这个原理可以实现前端微服务(微前端开发)!

cookies 不同端口 是可以共享的 - 走看看

六、js-cookie源码学习:

/*!
 * JavaScript Cookie v2.2.1
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
;(function (factory) {
  var registeredInModuleLoader;
  if (typeof define === 'function' && define.amd) {
    define(factory);
    registeredInModuleLoader = true;
  }
  if (typeof exports === 'object') {
    module.exports = factory();
    registeredInModuleLoader = true;
  }
  if (!registeredInModuleLoader) {
    var OldCookies = window.Cookies;
    var api = window.Cookies = factory();
    api.noConflict = function () {
      window.Cookies = OldCookies;
      return api;
    };
  }
}(function () {
  function extend () {
    var i = 0;
    var result = {};
    for (; i < arguments.length; i++) {
      var attributes = arguments[ i ];
      for (var key in attributes) {
        result[key] = attributes[key];
      }
    }
    return result;
  }
  function decode (s) {
    return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
  }
  function init (converter) {
    function api() {}
    function set (key, value, attributes) {
      if (typeof document === 'undefined') {
        return;
      }
      attributes = extend({
        path: '/'
      }, api.defaults, attributes);
      if (typeof attributes.expires === 'number') {
        attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
      }
      // We're using "expires" because "max-age" is not supported by IE
      attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
      try {
        var result = JSON.stringify(value);
        if (/^[\{\[]/.test(result)) {
          value = result;
        }
      } catch (e) {}
      value = converter.write ?
        converter.write(value, key) :
        encodeURIComponent(String(value))
          .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
      key = encodeURIComponent(String(key))
        .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
        .replace(/[\(\)]/g, escape);
      var stringifiedAttributes = '';
      for (var attributeName in attributes) {
        if (!attributes[attributeName]) {
          continue;
        }
        stringifiedAttributes += '; ' + attributeName;
        if (attributes[attributeName] === true) {
          continue;
        }
        // Considers RFC 6265 section 5.2:
        // ...
        // 3.  If the remaining unparsed-attributes contains a %x3B (";")
        //     character:
        // Consume the characters of the unparsed-attributes up to,
        // not including, the first %x3B (";") character.
        // ...
        stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
      }
      return (document.cookie = key + '=' + value + stringifiedAttributes);
    }
    function get (key, json) {
      if (typeof document === 'undefined') {
        return;
      }
      var jar = {};
      // To prevent the for loop in the first place assign an empty array
      // in case there are no cookies at all.
      var cookies = document.cookie ? document.cookie.split('; ') : [];
      var i = 0;
      for (; i < cookies.length; i++) {
        var parts = cookies[i].split('=');
        var cookie = parts.slice(1).join('=');
        if (!json && cookie.charAt(0) === '"') {
          cookie = cookie.slice(1, -1);
        }
        try {
          var name = decode(parts[0]);
          cookie = (converter.read || converter)(cookie, name) ||
            decode(cookie);
          if (json) {
            try {
              cookie = JSON.parse(cookie);
            } catch (e) {}
          }
          jar[name] = cookie;
          if (key === name) {
            break;
          }
        } catch (e) {}
      }
      return key ? jar[key] : jar;
    }
    api.set = set;
    api.get = function (key) {
      return get(key, false /* read as raw */);
    };
    api.getJSON = function (key) {
      return get(key, true /* read as json */);
    };
    api.remove = function (key, attributes) {
      set(key, '', extend(attributes, {
        expires: -1
      }));
    };
    api.defaults = {};
    api.withConverter = init;
    return api;
  }
  return init(function () {});
}));

七、相关内容:

Cookie、session Storage、local Storage、indexedDb

八、欢迎交流指正,关注我,一起学习。

相关文章
|
20天前
|
存储 搜索推荐 安全
Cookie 探秘:了解 Web 浏览器中的小甜饼
Cookie 探秘:了解 Web 浏览器中的小甜饼
|
2天前
更换了浏览器http代理ip使用不了的原因是什么
在互联网广泛应用的当下,http动态代理ip在各种业务中需求增加。然而,遇到更换浏览器http代理ip后无法使用的情况,可能由以下原因导致:1)ip稳定性差,导致网速过慢;2)ip已失效,提取后未及时使用会过期;3)ip纯净度低,免费代理ip质量通常不佳;4)并发量小,多个用户共享同一ip导致性能下降。为解决问题,用户需注意ip稳定性和时效性,选择高质量代理服务,并考虑并发使用情况。
44 1
更换了浏览器http代理ip使用不了的原因是什么
|
21天前
|
前端开发 JavaScript API
如何在不同浏览器中创建和使用 XMLHttpRequest 对象来执行 HTTP 请求
如何在不同浏览器中创建和使用 XMLHttpRequest 对象来执行 HTTP 请求
17 2
|
21天前
|
安全
关于浏览器警告提示 - This Set-Cookie header didn‘t specify a SameSite attribute
关于浏览器警告提示 - This Set-Cookie header didn‘t specify a SameSite attribute
199 0
|
21天前
|
Web App开发
允许浏览器cookie策略处理
允许浏览器cookie策略处理
17 0
|
21天前
|
存储 缓存
浏览器缓存sessionStorage、localStorage、Cookie
浏览器缓存sessionStorage、localStorage、Cookie
42 1
|
21天前
|
Web App开发 缓存 JSON
|
21天前
|
安全 算法 网络安全
浏览器 HTTPS 协议的相关知识点有哪些?
浏览器 HTTPS 协议的相关知识点有哪些?
26 0
|
21天前
|
存储 缓存 数据安全/隐私保护
HTTP之Session、Cookie 与 Application
HTTP之Session、Cookie 与 Application
33 0
|
21天前
|
安全 数据安全/隐私保护