Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the read and write operation of Cookie

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to realize the read and write operation of Cookie". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to read and write Cookie.

First, the emergence of Cookie

HTTP protocol is indispensable for the communication between browser and server, but because HTTP protocol is stateless, the server does not know what the browser did last time, which seriously hinders the implementation of interactive Web applications.

To solve the above problems, Netscape programmers created Cookie.

II. Transmission of Cookie

In the process of implementing the Cookie standard, the server needs to send Set-Cookie HTTP headers to any HTTP request as part of the response:

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

The browser stores such a Cookie and adds a Cookie HTTP request header for each subsequent request and sends it back to the server:

1. Cookie: name=value

The server determines which user the browser sends the request to by verifying the cookie value.

3. Cookie in browser

The Cookie in the browser mainly consists of the following parts:

Name: the unique name of Cookie, which must be encoded by URL. (overwrite occurs with the same name)

Value: must be URL encoded.

Domain (domain): cookie is valid for the current domain by default, and you can also set this value to ensure that it is valid for its subdomains.

Path (path): specifies the path under which Cookie is valid. The default is the current path.

Expiration time (expires): by default, the Cookie; will be deleted automatically at the end of the browser session, or you can set a date in GMT format to specify a specific deletion date; if you set the date to the previous date, Cookie will delete it immediately.

Security flag (secure): only Cookie is allowed to send to the https protocol after being specified.

When sending a request, the browser will only add the name and value to the Cookie field of the request header and send it to the server.

The browser provides a very poor API to manipulate Cookie:

1. [xss_clean]

You can write to the Cookie using the above method, and only one Cookie string can be written at a time:

1. [xss_clean] = 'axi1; secure; path=/'

Through this method, you can also read Cookie:

1. [xss_clean] / / "axi1"

As the above method to operate Cookie is not very intuitive, it is common to write some functions to simplify Cookie read, set and delete operations.

For the setting operation of Cookie, the following points are required:

URL encoding the name and value, that is, using the encodeURIComponent () method in JavaScript; expires requires that the date in GMT format be passed in a way that is easier to write, such as how to set the number of seconds; pay attention to the secure of only the attribute name

Each piece of information needs a semicolon plus a space.

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)

twenty-two。

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

24.

25. If (domain) {

twenty-six。 CookieStr + = `; domain=$ {domain}`

twenty-seven。 }

twenty-eight。

twenty-nine。 If (path) {

thirty。 CookieStr + = `; path=$ {path}`

thirty-one。 }

thirty-two。

thirty-three。 If (expires) {

thirty-four。 CookieStr + = `; expires=$ {expires}`

thirty-five。 }

thirty-six。

thirty-seven。 If (secure) {

thirty-eight。 CookieStr + = `; secure`

thirty-nine。 }

forty。

forty-one。 Return ([xss_clean] = cookieStr)

42.}

The read operation of Cookie needs to note that the name and value are decoded by URL, that is, the decodeURIComponent () method in JavaScript is called:

1. Function getCookie (name) {

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

3. Return

4.}

5. Let cookies = []

6. Let jar = {}

7. [xss_clean] & & (cookies = [xss_clean] .split (';'))

8.

9. For (let I = 0, max = cookies.length; I < max; iTunes +) {

10. Let [key, value] = cookies [I] .split ('=')

11. Key = decodeURIComponent (key)

Value = decodeURIComponent (value)

13. Jar [key] = value

14. If (key = name) {

15. Break

16.}

17.}

18.

19. Return name? Jar [name]: jar

20.}

The last method of cleanup is even simpler, as long as the expiration date (expires) is set to the past date:

1. Function removeCookie (key) {

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

3.}

After introducing the encapsulation of the basic operation of Cookie, you also need to understand that in order to limit the malicious use of Cookie, browsers specify the amount of disk space occupied by Cookie and the number of Cookie under each domain name.

4. Cookie on the server

Compared with the browser side, when the server performs the write operation of Cookie, it puts the stitched Cookie string into the Set-Cookie field of the response header; when performing the read operation of Cookie, it parses the key-value pair in the HTTP request header field Cookie.

The biggest difference from the browser is that the server is worried about the security of Cookie.

Signed

When signed=true is set, the server generates two Set-Cookie response header fields for the Cookie string:

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

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

Here, we verify that the Cookie has been tampered with during transmission by sending a name with the suffix .sig and a Cookie that encrypts the value.

HttpOnly

The httpOnly attribute is added to the server's Set-Cookie field. When the server contains a httpOnly field in the returned Cookie information, developers cannot manipulate the Cookie string through JavaScript.

The main advantage of this is that in the face of a XSS (Cross-site scripting) attack, the hacker cannot get the Cookie information that sets the httpOnly field.

At this point, you will find that localStorage is slightly inferior in defense against XSS attacks compared to Cookie. SameSite

Before introducing this new attribute, you need to understand that when a user initiates a http://b.com request from http://a.com, it also carries Cookie, and the Cookie brought from http://a.com is called a third-party Cookie.

Although third-party Cookie has some benefits, it gives CSRF (Cross-site request forgrey) the opportunity to attack.

In order to solve the root cause of the CSRF attack, the sameSite attribute shows up, and its values are as follows:

Strict: browsers will not carry Cookie in any cross-domain requests, which can effectively defend against CSRF attacks. However, for websites with multiple sub-domain names, the primary domain name is used to store user login information, and each sub-domain name requires the user to log in again, resulting in a very poor user experience.

Lax: compared to strict, it allows you to use Cookie when jumping from three-party websites.

To make it easier for you to understand the actual effect of sameSite, take a look at this example:

1. / / the a.com server will return the following Cookie when visiting the page

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

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

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

5.

6. / / the b.com server will return the following Cookie when visiting the page

7. Cookies.set ('foo',' asides, {sameSite: 'strict'})

8. Cookies.set ('bar',' baked, {sameSite: 'lax'})

9. Cookies.set ('baz',')

How to now the user click the link in a.com to jump to b.com, its request header is like this:

1. Request Headers

two。

3. Cookie: bar=b; baz=c

Fifth, website performance optimization

In the communication between the server and the browser, Cookie mainly depends on the response header and request header of HTTP, so Cookie will occupy a certain bandwidth.

As mentioned earlier, the browser will automatically carry Cookie information for every HTPP request, but for static resources within the same site, the server does not need to deal with the Cookie it carries, which is virtually a waste of bandwidth.

In best practice, static resources are typically deployed to separate domain names to avoid the impact of invalid Cookie.

At this point, I believe you have a deeper understanding of "how to achieve the read and write operation of Cookie". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report