cookie加密方式_了解HTTP Cookie的工作方式

cookie加密方式

介绍 (Introduction)

By using Cookies we can exchange information between the server and the browser to provide a way to customize a user session, and for servers to recognize the user between requests.

通过使用Cookies,我们可以在服务器和浏览器之间交换信息,以提供一种自定义用户会话的方式,并让服务器在请求之间识别用户。

HTTP is stateless, which means all request origins to a server are exactly the same and a server cannot determine if a request comes from a client that already did a request before, or it’s a new one.

HTTP是无状态的,这意味着到服务器的所有请求源都是完全相同的,并且服务器无法确定请求是否来自之前已经进行过请求的客户端,或者它是新请求。

Cookies are sent by the browser to the server when an HTTP request starts, and they are sent back from the server, which can edit their content.

当HTTP请求开始时,浏览器将cookie发送到服务器,然后将cookie从服务器发送回,后者可以编辑其内容。

Cookies are essentially used to store a session id.

Cookies本质上用于存储会话ID

In the past cookies were used to store various types of data, since there was no alternative. But nowadays with the Web Storage API (Local Storage and Session Storage) and IndexedDB, we have much better alternatives.

过去,由于没有其他选择,因此cookie用于存储各种类型的数据。 但是如今,有了Web Storage API (本地存储和会话存储)和IndexedDB ,我们有了更好的选择。

Especially because cookies have a very low limit in the data they can hold, since they are sent back-and-forth for every HTTP request to our server - including requests for assets like images or CSS / JavaScript files.

特别是因为cookie可以保存的数据的限制非常低,因为cookie是针对每个HTTP请求(包括对图像或CSS / JavaScript文件之类的资产的请求)来回发送给我们的服务器的。

Cookies have a long history, they had their first version in 1994, and over time they were standardized in multiple RFC revisions.

Cookies历史悠久,1994年发布了第一个版本,随着时间的推移,它们在多个RFC版本中进行了标准化。

RFC stands for Request for Comments, the way standards are defined by the Internet Engineering Task Force (IETF), the entity responsible for setting standards for the Internet

RFC代表“征求意见”,即标准由Internet工程任务组(IETF)定义的方式,IETF负责为Internet设置标准

The latest specification for Cookies is defined in the RFC 6265, which is dated 2011.

Cookies的最新规范在2011年的RFC 6265中定义。

Cookies的限制 (Restrictions of cookies)

  • Cookies can only store 4KB of data

    Cookies只能存储4KB数据

  • Cookies are private to the domain. A site can only read the cookies it set, not other domains cookies

    Cookies是该域专用的 。 网站只能读取其设置的Cookie,而不能读取其他域的Cookie

  • You can have up to 20 limits of cookies per domain (but the exact number depends on the specific browser implementation)

    每个域最多可以限制20个Cookie(但具体数量取决于特定的浏览器实现)
  • Cookies are limited in their total number (but the exact number depends on the specific browser implementation). If this number is exceeded, new cookies replace the older ones.

    Cookies的总数受限制(但确切的数目取决于特定的浏览器实现)。 如果超过此数目,则新的cookie会替换旧的cookie。

Cookies can be set or read server side, or client side.

Cookie可以设置或读取服务器端或客户端。

In the client side, cookies are exposed by the document object as document.cookie

在客户端,cookie被文档对象公开为document.cookie

设置饼干 (Set cookies)

The simplest example to set a cookie is:

设置cookie的最简单示例是:

document.cookie = 'name=Flavio'

This will add a new cookie to the existing ones (it does not overwrite existing cookies)

这会将新的cookie添加到现有的cookie中(不会覆盖现有的cookie)

The cookie value should be url encoded with encodeURIComponent(), to make sure it does not contain any whitespace, comma or semicolon which are not valid in cookie values.

cookie值应使用encodeURIComponent()进行url编码,以确保它不包含在cookie值中无效的任何空格,逗号或分号。

If you don’t set anything else, the cookie will expire when the browser is closed. To prevent so, add an expiration date, expressed in the UTC format (Mon, 26 Mar 2018 17:04:05 UTC)

如果您未进行其他设置,则Cookie将在浏览器关闭时失效。 为防止这种情况,请添加以UTC格式表示的到期日期( Mon, 26 Mar 2018 17:04:05 UTC )

document.cookie = 'name=Flavio; expires=Mon, 26 Mar 2018 17:04:05 UTC'

A simple JavaScript snippet to set a cookie that expires in 24 hours is:

一个简单JavaScript片段可以设置一个在24小时内过期的Cookie,该片段是:

const date = new Date()
date.setHours(date.getHours() + 24)
document.cookie = 'name=Flavio; expires=' + date.toUTCString()

Alternatively you can use the max-age parameter to set an expiration expressed in number of seconds:

另外,您可以使用max-age参数设置以秒为单位的到期时间:

document.cookie = 'name=Flavio; max-age=3600' //expires in 60 minutes
document.cookie = 'name=Flavio; max-age=31536000' //expires in 1 year

The path parameter specifies a document location for the cookie, so it’s assigned to a specific path, and sent to the server only if the path matches the current document location, or a parent:

path参数指定cookie的文档位置,因此将其分配给特定的路径,并且仅在该路径与当前文档位置或父级匹配时才发送到服务器:

document.cookie = 'name=Flavio; path=/dashboard'

this cookie is sent on /dashboard, /dashboard/today and other sub-urls of /dashboard/, but not on /posts for example.

这个cookie被上发送/dashboard/dashboard/today和其他子网址/dashboard/ ,而不是/posts的例子。

If you don’t set a path, it defaults to the current document location. This means that to apply a global cookie from an inner page, you need to specify path=/.

如果您未设置路径,则默认为当前文档位置。 这意味着要从内部页面应用全局cookie,您需要指定path=/

The domain can be used to specify a subdomain for your cookie.

domain可用于为您的Cookie指定一个子域。

document.cookie = 'name=Flavio; domain=mysite.com;'

If not set, it defaults to the host portion even if using a subdomain (if on subdomain.mydomain.com, by default it’s set to mydomain.com). Domain cookies are included in subdomains.

如果未设置,则即使使用子域,它也默认为主机部分(如果在subdomain.mydomain.com上,默认情况下设置为mydomain.com)。 域Cookie包含在子域中。

Secure (Secure)

Adding the Secure parameter makes sure the cookie can only be transmitted securely over HTTPS, and it will not be sent over unencrypted HTTP connections:

添加Secure参数可确保Cookie只能通过HTTPS安全地传输,并且不会通过未加密的HTTP连接发送:

document.cookie = 'name=Flavio; Secure;'

Note that this does not make cookies secure in any way - always avoid adding sensitive information to cookies

请注意,这不会以任何方式确保cookie的安全-始终避免向cookie添加敏感信息

HttpOnly (HttpOnly)

One useful parameter is HttpOnly, which makes cookies inaccessible via the document.cookie API, so they are only editable by the server:

一个有用的参数是HttpOnly ,它使cookie无法通过document.cookie API进行访问,因此它们只能由服务器编辑:

document.cookie = 'name=Flavio; Secure; HttpOnly'

SameSite (SameSite)

SameSite, unfortunately still not supported by all browsers (but many do! https://caniuse.com/#feat=same-site-cookie-attribute, lets servers require that a cookie is not sent on cross-site requests, but only on resources that have the cookie domain as the origin, which should be a great help towards reducing the risk of CSRF (Cross Site Request Forgery) attacks.

SameSite ,可惜还是没有被所有的浏览器(但很多人的支持! https://caniuse.com/#feat=same-site-cookie-attribute只,让服务器需要一个cookie不会在跨站点请求发送,但以Cookie域为源的资源,这对于降低CSRF(跨站点请求伪造)攻击的风险应该有很大的帮助。

To update the value of a cookie, just assign a new value to the cookie name:

要更新cookie的值,只需为cookie名称分配一个新值:

document.cookie = 'name=Flavio2'

Similar to updating the value, to update the expiration date, reassign the value with a new expires or max-age property:

与更新值类似,要更新到期日期,请使用新的expiresmax-age属性重新分配值:

document.cookie = 'name=Flavio; max-age=31536000' //expires in 1 year

Just remember to also add any additional parameters you added in the first place, like path or domain.

只需记住还要添加您首先添加的任何其他参数,例如pathdomain

To delete a cookie, unset its value and pass a date in the past:

要删除Cookie,请取消设置其值并传递过去的日期:

document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'

(and again, with all the parameters you used to set it)

(同样,使用您用来设置它的所有参数)

访问Cookies值 (Access the cookies values)

To access a cookie, lookup document.cookie:

要访问cookie,请查询document.cookie

const cookies = document.cookie

This will return a string with all the cookies set for the page, semicolon separated:

这将返回一个字符串,其中包含该页面的所有cookie,并以分号分隔:

'name1=Flavio1; name2=Flavio2; name3=Flavio3'
//ES5
if (
  document.cookie.split(';').filter(item => {
    return item.indexOf('name=') >= 0
  }).length
) {
  //name exists
}

//ES2016
if (
  document.cookie.split(';').filter(item => {
    return item.includes('name=')
  }).length
) {
  //name exists
}

抽象库 (Abstractions libraries)

There are a number of different libraries that will provide a friendlier API to manage cookies. One of them is https://github.com/js-cookie/js-cookie, which supports up to IE7, and has a lot of stars on GitHub (which is always good).

有许多不同的库将提供更友好的API来管理cookie。 其中之一是https://github.com/js-cookie/js-cookie ,它最多支持IE7,并且在GitHub上有很多明星(这总是很好)。

Some examples of its usage:

其用法的一些示例:

Cookies.set('name', 'value')
Cookies.set('name', 'value', {
  expires: 7,
  path: '',
  domain: 'subdomain.site.com',
  secure: true
})

Cookies.get('name') // => 'value'
Cookies.remove('name')

//JSON
Cookies.set('name', { name: 'Flavio' })
Cookies.getJSON('name') // => { name: 'Flavio' }

Use that or the native Cookies API?

使用该还是本机Cookies API?

It all comes down to adding more kilobytes to download for each user, so it’s your choice.

所有这些都归结为每个用户增加了更多的千字节下载量,因此这是您的选择。

在服务器端使用Cookies (Use cookies server-side)

Every environment used to build an HTTP server allows you to interact with cookies, because cookies are a pillar of the Modern Web, and not much could be built without them.

用于构建HTTP服务器的每个环境都允许您与Cookie进行交互,因为Cookie是现代Web的基础,没有Cookie便无法构建太多环境。

PHP has $_COOKIE Go has cookies facilities in the net/http standard library

PHP的$ _COOKIE Go在net/http标准库中具有cookie功能

and so on.

等等。

Let’s do an example with Node.js

让我们以Node.js为例

When using Express.js, you can create cookies using the res.cookie API:

使用Express.js时,可以使用res.cookie API创建cookie:

res.cookie('name1', '1Flavio', {
  domain: '.example.com',
  path: '/admin',
  secure: true
})
res.cookie('name2', 'Flavio2', {
  expires: new Date(Date.now() + 900000),
  httpOnly: true
})
res.cookie('name3', 'Flavio3', { maxAge: 900000, httpOnly: true })

//takes care of serializing JSON
res.cookie('name4', { items: [1, 2, 3] }, { maxAge: 900000 })

To parse cookies, a good choice is to use the https://github.com/expressjs/cookie-parser middleware. Every Request object will have cookies information in the req.cookie property:

要解析cookie,一个不错的选择是使用https://github.com/expressjs/cookie-parser中间件。 每个Request对象在req.cookie属性中都具有cookie信息:

req.cookies.name //Flavio
req.cookies.name1 //Flavio1

If you create your cookies using signed: true:

如果您使用signed: true创建cookie signed: true

res.cookie('name5', 'Flavio5', { signed: true })

they will be available in the req.signedCookies object instead. Signed cookies are protected against modifications on the client. The signature used to sign a cookie value makes sure that you can know, server-side, if the client has modified it.

它们将改为在req.signedCookies对象中可用。 已签名的cookie可以防止在客户端上进行修改。 用于对cookie值进行签名的签名可确保您可以在服务器端知道客户端是否已对其进行了修改。

https://github.com/expressjs/session and https://github.com/expressjs/cookie-session are two different middleware options to build cookie-based authentication, which one to use depends on your needs.

https://github.com/expressjs/sessionhttps://github.com/expressjs/cookie-session是用于构建基于cookie的身份验证的两种不同的中间件选项,根据您的需要使用哪种。

使用浏览器DevTools检查Cookie (Inspect cookies with the Browser DevTools)

All browsers in their DevTools provide an interface to inspect and edit cookies.

DevTools中的所有浏览器提供了一个界面,用于检查和编辑Cookie。

Chrome (Chrome)

Chrome devtools cookies

火狐浏览器 (Firefox)

Firefox devtools cookies

苹果浏览器 (Safari)

Safari devtools cookies

Cookie的替代品 (Alternatives to cookies)

Are cookies the only way to build authentication and sessions on the Web?

Cookies是在Web上建立身份验证和会话的唯一方法吗?

No! There is a technology that recently got popular, called JSON Web Tokens (JWT), which is a Token-based Authentication.

没有! 最近有一种流行的技术称为JSON Web令牌 ( JWT ),它是基于令牌的Authentication

翻译自: https://flaviocopes.com/cookies/

cookie加密方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值