Detailed Explanation of Cookies

Cookie

Why use cookies?

The HTTP protocol itself is stateless. What is stateless, that is, the server cannot determine the identity of the user. Cookies can record the identity of visitors.
Usually, cookies are used to record identities, and the simplest use is the login function.
There is also an implementation that can be used as a global variable to track user behavior.

What are cookies?

The client initiates a request to the server, and if the server needs to record the user status, it uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the website again, the browser submits the requested URL together with the cookie to the server. The server checks the cookie to identify the user status.
A cookie is a mechanism provided by browsers that provides the cookie property of the document object to JavaScript. It can be controlled by JavaScript, not by the nature of JavaScript itself. A cookie is a file stored on the user's hard disk. This file usually corresponds to a domain name. When the browser accesses the domain name again, the cookie is made available. Therefore, cookies can span multiple web pages under one domain name, but cannot be used across multiple domain names.

How are cookies used?

Basic process:
When a user visits and logs in to a website for the first time, the setting and sending of cookies will go through the following four steps: the
client sends a request to the server --" the server sends an HttpResponse response to the client, which contains Set -Cookie header--"The client saves the cookie, and when it sends a request to the server later, the HttpRequest request will contain a Cookie header--"The server returns the response data [
External link picture transfer failed, the source site may have anti-theft Chain mechanism, it is recommended to save the picture and upload it directly (img-Cs9ag3EJ-1691721601938)(vx_images/303144440647148.png)]

Common attributes of cookies

A cookie contains the following information:
1) Cookie name. The cookie name must use characters that can only be used in URLs, generally letters and numbers, and cannot contain special characters. If there are special characters, you want to transcode them. For example, when js operates cookies, escape() can be used to transcode the name.
2) Cookie value, the cookie value is the same as the name of the cookie, which can be transcoded and encrypted.
3) Expires, expiration date, a time in GMT format. After this date, the browser will delete the cookie. When this is not set, the cookie will disappear after the browser is closed.
4) Path, a path, the page under this path can access the cookie, generally set to "/", to indicate that all pages of the same site can access this cookie.
5) Domain, sub-domain, specify that Cookies can only be accessed under this sub-domain. For example, if you want Cookies to be accessible under a.test.com but not under b.test.com, you can set the domain to a .test.com.
6) Secure, security, specifies whether the cookie can only be accessed through the https protocol, general cookies can be accessed using the HTTP protocol, if Secure (no value) is set, the cookie can only be accessed by the page when the https protocol is used to connect .
7) HttpOnly, if the "HttpOnly" attribute is set in the cookie, the cookie information cannot be read through the program (JS script, Applet, etc.).
8) samesite attribute
If the attribute SameSite of Cookie is not configured or configured as none, there is a CSRF risk.
The value of SameSite can be:
unset (default). In this case the browser may adopt its own strategy.
none. There is a CSRF risk.
lax. In most cases, third-party cookies are not sent, except for Get requests that navigate to the target URL.
strict. Third-party cookies are completely prohibited, and no cookies are sent under any circumstances when crossing sites. In other words, only when the URL of the current web page is consistent with the request target, the cookie will be brought

Modification and deletion:

The cookie operation provided by HttpServletResponse has only one addCookie(Cookie cookie), so if you want to modify a cookie, you can only use a cookie with the same name to overwrite the original cookie. If you want to delete a cookie, you only need to create a new cookie with the same name, set maxAge to 0, and overwrite the original cookie.
For a newly created cookie, attributes other than value and maxAge, such as name, path, and domain must be consistent with the original ones to achieve the effect of modification or deletion. Otherwise, the browser will treat it as two different cookies and not overwrite them.
It is worth noting that when reading cookies from the client, other attributes including maxAge are not readable and will not be submitted. When the browser submits the cookie, it will only submit the name and value attributes. The maxAge attribute is only used by the browser to determine whether the cookie has expired, not by the server.
Cookie cookie = new Cookie("mcrwayfun",System.currentTimeMillis()+"");
// set the life cycle to MAX_VALUE, permanent,
cookie.setMaxAge(Integer.MAX_VALUE);
resp.addCookie(cookie);

view cookies in browser

View the cookie of the current page
f12 Enter the application as the global cookie
The request cookie and return cookie of the currently visited URL
insert image description here

You can also enter
the console with f12 through the command mode
: javascript:alert(document.cookie)

Front-end page reads cookies

write cookie

function writeCookie() {
document.cookie="userId=828";
//如果要一次存储多个名/值对,可以使用分号加空格(; )隔开,例如
document.cookie="userId=828; userName=hulk";
alert("操作成功");
}

Use the escape() function to encode, it can express some special symbols in hexadecimal, for example, a space will be encoded as "20%", so that it can be stored in the cookie value, and using this scheme can also avoid Chinese garbled characters appear.
For example

document.cookie="str="+escape("I love ajax"); 

After using escape() to encode, you need to use unescape() to decode after taking out the value to get the original cookie value.
You can only get all the cookie values ​​at once, but you cannot specify the cookie name to get the specified value. This is the most troublesome part of handling cookie values. Users must analyze this string by themselves to obtain the specified cookie value
Read cookie

document.cookie="userId=828";
document.cookie="userName=hulk";
//获取cookie字符串
var strCookie=document.cookie;
//将多cookie切割为多个名/值对
var arrCookie=strCookie.split("; ");
var userId;
//遍历cookie数组,处理每个cookie对
for(var i=0;i<arrCookie.length;i++){
var arr=arrCookie[i].split("=");
//找到名称为userId的cookie,并返回它的值
if("userId"==arr[0]){
userId=arr[1];
break;
}
}
alert(userId);

Delete cookie
If you want a cookie to be invalid, then set the expires of this cookie to a certain time in the past

//获取当前时间 
var date=new Date(); 
//将date设置为过去的时间 
date.setTime(date.getTime()-10000); 
//将userId这个cookie删除 
document.cookie="userId=828; expires="+date.toGMTString(); 

Java backend reads and writes cookies

The servlet sets the pass directly:

Cookie cookie = new Cookie("color", URLEncoder.encode("黄色", "UTF-8"));
Cookie name = new Cookie("name", URLEncoder.encode("zhang三", "UTF-8"));
// 设置过期时间为24小时,以秒为单位
cookie.setMaxAge(60 * 60 * 24);
name.setMaxAge(60 * 60 * 1);
// 添加cookie
response.addCookie(cookie);
response.addCookie(name);
request.getRequestDispatcher("/cookie.html").forward(request, response);

Get the front-end cookie and set it

request.setCharacterEncoding("UTF-8");
Map<String, String> returnMap = new HashMap<>();
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
returnMap.put(name, value);
}
Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
returnMap.put(entry.getKey(), entry.getValue()[0]);
}

The most typical cookie – JESSIONID

what is it

First of all, JSESSIONID is a cookie, which is used by Servlet containers (tomcat, jetty) to record user sessions.
Generally, there is a sessionID in the cookie, and the default cookie name used to store the sessionID in each language is different, as follows:
asp: ASPSESSIONID
php: PHPSESSIONID
jsp: JSESSIONID

When to Plant JSESSIONID?

When creating a session, that is, when calling request.getSession(), I won't say anything about getSession. Accessing html will not create a session, and the JSP page will create a session by default, you can turn off the automatic session creation in the JSP page

how to use?

In logout login, login timeout add:

//HttpServletRequest request
HttpSession session = request.getSession();
session.invalidate();

session.invalidate() is to set the session to be invalid. It is generally used when exiting, but it should be noted that the browser will immediately create a new session when the session is invalid. JSESSIONID is just the name of the session id in tomcat. In other containers, it is not necessarily called JSESSIONID.
When session.invalidate() executes this code, JSESSIONID will become invalid, and the browser will immediately create a new JSESSIONID.
Call the isRequestedSessionIdFromCookie of the Request object to determine whether the client cookie is available. The logic inside is also very simple, that is, to read whether there is a JSESSIONID cookie in the request. So some people on the Internet say that it is the first visit. In fact, as long as the client does not pass the JSESSIONID, tomcat assumes that the cookie is not available.

jsessionid = request.getSession().getId()
sessio(获取session并将数据更新
// 开始一个新的 session
         HttpSession session = req.getSession();
         //首先将原session中的数据转移至一临时map中
         Map<String,Object> tempMap = new HashMap();
         Enumeration<String> sessionNames = session.getAttributeNames();
         while(sessionNames.hasMoreElements()){
             String sessionName = sessionNames.nextElement();
             tempMap.put(sessionName, session.getAttribute(sessionName));
             System.out.println(sessionName);
         }
         //注销原session,为的是重置sessionId
         session.invalidate();
         //将临时map中的数据转移至新session
         session = req.getSession();
         for(Map.Entry<String, Object> entry : tempMap.entrySet()){
             session.setAttribute(entry.getKey(), entry.getValue());

Restrictions on the use of cookies

The cookie size is limited during WEB development
1. The number of cookies allowed by each domain name in the browser:
  Microsoft pointed out that Internet Explorer 8 increases the cookie limit to 50 per domain name, but IE7 also seems to allow 50 cookies per domain name.
  Firefox has a limit of 50 cookies per domain.
  Opera has a limit of 30 cookies per domain.
  Safari/WebKit does not seem to have cookie restrictions. But if there are many cookies, the header size will exceed the processing limit of the server, which will cause errors.
  NOTE: "Limit 20 cookies per domain" will no longer be true! But in order to be compatible with lower versions, we try to control the number of cookies to 20 or less.
2. When many cookies are set, how does the browser respond.
  Except for Safari (you can set all cookies, regardless of the number), there are two methods:
  the least recently used (least recently used (LRU)) method: when the cookie has reached the limit, the oldest cookie is automatically kicked out, so that the latest cookie some space. Internet Explorer and Opera use this method.
  Firefox is unique: while the last set cookie is always kept, it seems to randomly decide which cookies are kept without any plan.
  Suggestion: Do not exceed the cookie limit in Firefox
3. The total size of cookies varies between different browsers:
  Firefox and Safari allow cookies up to 4097 bytes, including name (name), value (value) and an equal sign.
  Opera allows cookies up to 4096 bytes, including: name (name), value (value) and the equal sign.
  Internet Explorer allows cookies up to 4095 bytes, including: name (name), value (value) and the equal sign.
  Note: Multibyte characters count as two bytes. In all browsers, any cookie size larger than the limit is ignored and never set. In this case, in order to be compatible with lower versions, we try to control the cookie size to 4095 or less

Cookie Security Policy

1. The sensitive information saved in the cookie must be encrypted.
2. Set HttpOnly to true
  1). The function of this attribute value is to prevent the cookie value from being read by the page script. In other words, when the HTTPOnly attribute of the cookie is set to True (default is false), the cookie will not be found in the document object.
  2), but setting the HttpOnly attribute, the HttpOnly attribute only increases the difficulty of the attacker, and the threat of cookie theft has not been completely eliminated, because it is still possible for the cookie to be intercepted and captured during the transmission process and leak information.
3) The cookie that stores sessionID in the website must be set. This is why AWVS named the vulnerability as Session Cookie without Secure flag set. General website applications will not operate these sensitive cookies in js, and we will not set some cookies that need to be operated with JS in the application. In this way, the security of cookie information is guaranteed, and the normal business of the website is guaranteed at the same time.
2. Set Secure to true
  1) When setting this attribute for a cookie, the browser will only send the cookie when accessing under the https protocol.
2) Setting the cookie to secure only ensures that the data transmission process between the cookie and the WEB server is encrypted, while the cookie file stored locally is not encrypted. If you want to encrypt local cookies, you have to encrypt the data yourself.
3. Set the validity period for the cookie
   1), if the validity period is not set, in case the user obtains the user's cookie, he can always log in as the user.
 2) When setting cookie authentication, two times need to be added, one is "even if it is active all the time, it will expire" time, and the other is "expiration time of long-term inactivity", and in web applications, first Determine whether the two times have timed out before performing other operations.
4. Do not store important and sensitive data in cookies, and the storage must be encrypted.

Too many cookies will bring huge performance waste

The cookie is followed by the domain name. All requests under the same domain name will carry cookies. Just imagine, if we just request a picture or a CSS file at the moment, we have to run around with a cookie (the key is that the information stored in the cookie is not needed), what a waste of time and money. Although cookies are small, there can be many requests. With the superposition of requests, the overhead caused by such unnecessary cookies will be unimaginable.
Cookies are used to maintain user information, and all requests under the domain name (domain) will carry cookies, but for requests for static files, carrying cookie information is useless at all. The domain name of the website is resolved separately. - Since the Cookie in the HTTP request is passed in clear text, security is a problem unless HTTPS is used.

storage method

Older storage methods:
cookie
userDate (ie5.0)
html5 storage in three ways
local storage (permanent storage, stored in the cache. Clearing method: manual clearing or browser cache invalidation)
application cache
indexed DB

Guess you like

Origin blog.csdn.net/Artisan_w/article/details/132226186
Recommended