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

news/2024/5/18 12:40:31 标签: 浏览器, 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

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

参考链接:

JavaScript Cookie | 菜鸟教程

无状态的HTTP和它的Cookie_zzb_的博客-CSDN博客

HTTP无状态与Cookie、Session、Token_Mrlijie00的博客-CSDN博客

cookie(储存在用户本地终端上的数据)_百度百科

cooiek的Secure属性设置_weixin_52164116的博客-CSDN博客_seckey_abvk

浏览器Cookie详解_huangpb0624的博客-CSDN博客_浏览器cookie

浏览器Cookie详解_zjl_712、的博客-CSDN博客_浏览器cookie


http://www.niftyadmin.cn/n/20788.html

相关文章

第三十章 数论——扩展中国剩余定理

第三十章 数论——扩展中国剩余定理一、中国剩余定理的弊端二、扩展中国剩余定理1、作用2、内容3、问题4、代码一、中国剩余定理的弊端 在第二十九章中&#xff0c;作者详细地讲解了中国剩余定理的使用&#xff0c;在开始本章节的讲解之前&#xff0c;建议读者先去看上一章节的…

微信小程序 Spdier - OfferShow 反编译逆向(一)

微信小程序 Spdier - OfferShow 反编译逆向&#xff08;一&#xff09; 文章目录微信小程序 Spdier - OfferShow 反编译逆向&#xff08;一&#xff09;前言一、任务说明1.尝试反编译分析出js_code参数的生成方式&#xff0c;用来获取token2.将小程序搜索出来的数据保存至本地e…

深入学习Vue.js(一)Vue.js的设计思路

文章目录1.命令式和声明式2.性能3.运行时和编译时4.声明式地描述UI5.将虚拟DOM渲染为真实DOM1.命令式和声明式 视图层框架通常分为命令式和声明式。 &#xff08;1&#xff09;命令式 ​ jQuery就是一种典型的命令式框架&#xff0c;该类框架的特点是关注过程。即代码描述的是…

面试官:系统需求多变时如何设计?

面试官&#xff1a;我想问个问题哈&#xff0c;项目里比较常见的问题 面试官&#xff1a;我现在有个系统会根据请求的入参&#xff0c;做出不同动作。但是&#xff0c;这块不同的动作很有可能是会发生需求变动的&#xff0c;这块系统你会怎么样设计&#xff1f; 面试官&#…

每日一练c++题目日刊 | 第八期

文章目录第一题&#xff1a;夏洛克侦案题目描述输入格式输出格式输入样例输出样例解题思路&C题解第一题&#xff1a;夏洛克侦案 题目描述 福尔摩斯接到了一个任务&#xff0c;需要帮助一位富有的英国贵族解决一件谋杀案。谋杀发生在他的豪宅里&#xff0c;在他的书房里。…

【3D游戏基础】蒙皮骨骼动画与骨架

效果目标&#xff01;画出蒙皮动画的骨架。视频https://www.bilibili.com/video/BV1pM411m7YwPPThttps://zfxdvouj61.feishu.cn/file/boxcnwgESO6zdQetO7oNhKboNsd以下为PPT文字稿&#xff0c;建议还是看视频讲讲自己对蒙皮骨骼动画的理解&#xff0c;并在 Cocos Creator 3.6 中…

<flutter>跨平台开发新手入坑指南 dart dio pubspec.yaml json_annotation 打包 小坑指南

1.资源文件和依赖三方包&#xff08;pubspec.yaml&#xff09;&#xff1a; pubspec.yaml文件可以说是和安卓的gradle文件差不多&#xff0c;它用来描述版本号、sdk、依赖等的。 在资源导入方面同安卓不一样的是&#xff0c;flutter需要在pubspec.yaml中声名&#xff0c;不然…

SpringCloud-Gateway配置及持久化、过滤器、异常处理

文章目录yml配置代码配置持久化数据结构predicates(断言) 和filters&#xff08;过滤&#xff09;新增配置说明相关接口全局过滤器局部过滤器全局异常处理gateway不能和web一起使用 需要排除掉<dependency><groupId>org.springframework.cloud</groupId><…