Good web front-end programmers to share knowledge Cookie

  Good programmers web front-end share Cookie knowledge , today small dry goods brought a writeup for everyone, then let's take a look at it .

  A, Cookie appear

  Between the browser and server communication and ultimately, HTTP protocol, but because the HTTP protocol is stateless, so the server does not know the last time the browser do what kind of operation, so serious impediment to the Interactive Web Application Program.

  In response to these problems, Netscape programmers created the Cookie .

  Two, cookies transmission

  In the server side achieve Cookie is standard procedure, the need for any HTTP request Set-Cookie HTTP header as part of the response:

  1. Set-Cookie: name=value; expires=Tue, 03-Sep-2019 14:10:21 GMT; path=/; domain=.xxx.com;

  This browser will store Cookie , and add for each request after the Cookie HTTP request hair back to the server:

  1. Cookie: name=value

  Server by verifying Cookie value, the browser sends the request to determine which user belongs.

  Third, the browser Cookie

  Browser Cookie mainly consists of the following components:

  · Name: Cookie unique name must be URL encoding process. ( Of the same name will appear in the case covered )

  · Values: must be URL handling code.

  · Domain (Domain) : By default, the cookie is valid, you can also set the value in the current field to ensure the effectiveness of its subdomains.

  · Path (path) : Specifies the Cookie in which the path is valid, the default is the current path.

  Expiry Time (the Expires) : By default, it will be automatically deleted at the end of the browser session Cookie; can also set a GMT date format, assign specific deletion date ; If the date set for the previous date, then the Cookie will be deleted immediately .

  · Safety signs (Secure) : After specifying only allowed Cookie sent to the https protocol.

  When the browser sends a request, will only add to the request header names and values of the Cookie field, is sent to the server.

  Browser provides a very crappy API to manipulate Cookie :

  1. document.cookie

  The above method can Cookie write operation, a write only every Cookie string:

  1. document.cookie = 'a=1; secure; path=/'

  By this method may also be Cookie read operation:

  1. document.cookie // "a=1"

  Since the above method of operating a Cookie very intuitive, usually write functions to simplify Cookie read, set, and delete operations.

  For Cookie settings operation, you need the following:

  For the values for the name and URL encoding process, i.e. using JavaScript in the encodeURIComponent () method ; expires claim incoming GMT date format is easier to deal with ways of writing, such as: the number of seconds set manner ; note that only the property name the secure;

  Each piece of information requires the use of a semicolon spaces.

  1. function setCookie (key, value, attributes) {

  2. if (typeof document === 'undefined') {

  3. return

  4. }

  5. attributes = Object.assign({}, {

  6. path: '/'

  7. }, attributes)

  8.

  9. let { domain, path, expires, secure } = attributes

  10.

  11. if (typeof expires === 'number') {

  12. expires = new Date(Date.now() + expires * 1000)

  13. }

  14. if (expires instanceof Date) {

  15. expires = expires.toUTCString()

  16. } else {

  17. expires = ''

  18. }

  19.

  20. key = encodeURIComponent(key)

  21. value = encodeURIComponent(value)

  22.

  23. let cookieStr = `${key}=${value}`

  24.

  25. if (domain) {

  26. cookieStr += `; domain=${domain}`

  27. }

  28.

  29. if (path) {

  30. cookieStr += `; path=${path}`

  31. }

  32.

  33. if (expires) {

  34. cookieStr += `; expires=${expires}`

  35. }

  36.

  37. if (secure) {

  38. cookieStr += `; secure`

  39. }

  40.

  41. return (document.cookie = cookieStr)

  42.}

  Cookie的读操作需要注意的是将名称与值进行URL解码处理,也就是调用JavaScript中的decodeURIComponent()方法:

  1. function getCookie (name) {

  2. if (typeof document === 'undefined') {

  3. return

  4. }

  5. let cookies = []

  6. let jar = {}

  7. document.cookie && (cookies = document.cookie.split('; '))

  8.

  9. for (let i = 0, max = cookies.length; i < max; i++) {

  10. let [key, value] = cookies[i].split('=')

  11. key = decodeURIComponent(key)

  12. value = decodeURIComponent(value)

  13. jar[key] = value

  14. if (key === name) {

  15. break

  16. }

  17. }

  18.

  19. return name ? jar[name] : jar

  20.}

  最后一个清除的方法就更加简单了,只要将失效日期(expires)设置为过去的日期即可:

  1. function removeCookie (key) {

  2. setCookie(key, '', { expires: -1 })

  3. }

  介绍Cookie基本操作的封装之后,还需要了解浏览器为了限制Cookie不会被恶意使用,规定了Cookie所占磁盘空间的大小以及每个域名下Cookie的个数。

  四、服务端的Cookie

  相比较浏览器端,服务端执行Cookie的写操作时,是将拼接好的Cookie字符串放入响应头的Set-Cookie字段中;执行Cookie的读操作时,则是解析HTTP请求头字段Cookie中的键值对。

  与浏览器最大的不同,在于服务端对于Cookie的安全性操碎了心

  signed

  当设置signed=true时,服务端会对该条Cookie字符串生成两个Set-Cookie响应头字段:

  1. Set-Cookie: lastTime=2019-03-05T14:31:05.543Z; path=/; httponly

  2. Set-Cookie: lastTime.sig=URXREOYTtMnGm0b7qCYFJ2Db400; path=/; httponly

  这里通过再发送一条以.sig为后缀的名称以及对值进行加密的Cookie,来验证该条Cookie是否在传输的过程中被篡改。

  httpOnly

  服务端Set-Cookie字段中新增httpOnly属性,当服务端在返回的Cookie信息中含有httpOnly字段时,开发者是不能通过JavaScript来操纵该条Cookie字符串的。

  这样做的好处主要在于面对XSS(Cross-site scripting)***时,***无法拿到设置httpOnly字段的Cookie信息。

  此时,你会发现localStorage相比较Cookie,在XSS***的防御上就略逊一筹了。 sameSite

  在介绍这个新属性之前,首先你需要明白:当用户从http://a.com发起http://b.com的请求也会携带上Cookie,而从http://a.com携带过来的Cookie称为第三方Cookie

  虽然第三方Cookie有一些好处,但是给CSRF(Cross-site request forgrey)***的机会。

  为了从根源上解决CSRF***,sameSite属性便闪亮登场了,它的取值有以下几种:

  · strict:浏览器在任何跨域请求中都不会携带Cookie,这样可以有效的防御CSRF***,但是对于有多个子域名的网站采用主域名存储用户登录信息的场景,每个子域名都需要用户重新登录,造成用户体验非常的差。

  · lax:相比较strict,它允许从三方网站跳转过来的时候使用Cookie

  为了方便大家理解sameSite的实际效果,可以看这个例子:

  1. // a.com 服务端会在访问页面时返回如下Cookie

  2. cookies.set('foo', 'aaaaa')

  3. cookies.set('bar', 'bbbbb')

  4. cookies.set('name', 'cccccc')

  5.

  6. // b.com 服务端会在访问页面时返回如下Cookie

  7. cookies.set('foo', 'a', { sameSite: 'strict' })

  8. cookies.set('bar', 'b', { sameSite: 'lax' })

  9. cookies.set('baz', 'c')

  如何现在用户在a.com中点击链接跳转到b.com,它的请求头是这样的:

  1. Request Headers

  2.

  3. Cookie: bar=b; baz=c

  五、网站性能优化

  Cookie在服务端和浏览器的通信中,主要依靠HTTP的响应头和请求头传输的,所以Cookie会占据一定的带宽。

  前面提到浏览器会为每一次HTPP请求自动携带上Cookie信息,但是对于同站内的静态资源,服务器并不需要处理其携带的Cookie,这无形中便浪费了带宽。

  在最佳实践中,一般都会将静态资源部署到独立的域名上,从而可以避免无效Cookie的影响。

  希望本篇文章能够对正在从事Web 前端工作和准备从事Web 前端学习的小伙伴们有所帮助。


Guess you like

Origin blog.51cto.com/14249543/2416722