Introduction to the

Cookies and sessions are often used in the past, but a new browser local caching scheme is introduced in H5. Because people are using less standard as a local storage tool, the next request will default to the cookie data, resulting in wasted performance and traffic.

The following will introduce why cookie is generated from the beginning, what problems it appears to solve and what problems it has; Behind localStorage is why, it solves that part of the problem. Finally, compare cookie, session, localStorage and sessionStorage.

cookie

First of all, why do cookies happen? What is a cookie?

What is cookie and why

When an HTTP request is made to establish a connection, there is a connection between the client and the server. However, each HTTP connection is independent, which can also be said to be stateless.

  • When a client logs in to the client for the first time, the server verifies the login information and generates a Token so that subsequent requests do not need to be re-logged in
  • The second time the connection is established, the client carries the Token returned by the server upon successful login, but where should the Token be stored? It’s usually stored in cookies.

To summarize, because HTTP is stateless, clients need a cookie to store it.

HTTP CookieA Web Cookie (also called a Web Cookie or browser Cookie) is a small piece of data that the server sends to the user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server.

Cookies are mainly used for the following three aspects:

  • Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  • Personalization (such as user-defined Settings, themes, etc.)
  • Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.)

Create a Cookie

When the server receives an HTTP request, it can add a set-cookie option to the response header. After receiving the response, the browser usually saves the Cookie and sends the Cookie information to the server through the Cookie request header in each subsequent request to the server.

There are a number of attributes you can set when creating a Cookie, such as Expires, max-age, Domain, Path, Secure, and HttpOnly, because it is automatically carried to the server and supports server-side Settings. So there are a lot of things to pay attention to, like timeliness, scope, security. Here are three ways to explain the use of his attributes.

timeliness

If the time-validity of the Cookie is not Set through the Expries and max-age fields in set-cookie, the Cookie is a simple session-duration Cookie. It is automatically deleted when the browser is closed.

If Expries and max-age are set, the Cookie is valid for the specified time.

Tip: When Cookie expiration is set, the date and time are only relevant to the client, not the server.

scope

The Domain and Path identifiers define the scope of the Cookie: that is, which urls the Cookie should be sent to.

The Domain identifier specifies which hosts can accept cookies. If this parameter is not specified, it defaults to the host of the current document (excluding the subdomain name). If Domain is specified, subdomain names are generally included.

The Path identifier specifies which paths under the host can accept cookies (the URL Path must exist in the request URL). Child paths are also matched with the character %x2F (“/”) as the path separator.

security

Cookies marked Secure should only be sent to the server through requests that are encrypted by the HTTPS protocol. But even if Secure flags are set, sensitive information should not be transmitted through cookies because cookies are inherently insecure and Secure flags do not provide a guarantee of security.

As of Chrome 52 and Firefox 52, insecure sites (HTTP 🙂 cannot use the Secure flag of cookies.

To avoid cross-domain scripting (XSS) attacks, cookies with HttpOnly tags cannot be accessed through JavaScript’s Document.cookie API; they should only be sent to the server.

The client operates on cookies

New cookies can be created through the document. cookie property, and cookies that are not HttpOnly tagged can be accessed through this property.

  documnet.cookie
  // There is an article devoted to it
Copy the code

The characteristics of the cookie

advantages

  • Store user information (user token)
  • Marking user behavior (UUID, buried point)

disadvantages

  • Cookies are attached to every HTTP request, so they add traffic

  • Cookies may be disabled. If a user is concerned about privacy, he is likely to disable cookies in his browser.

  • Because cookies in HTTP requests are passed in plain text, there is a potential security risk that cookies can be tampered with

  • Limits on the number and length of cookies. Each Domain under Internet Explorer 6 or Internet Explorer 6-(IE6 below) : maximum 20 cookies Internet Explorer 7 or Internet Explorer 7+(IE7 above) : Up to 50 cookies FF: up to 50 cookies Opera: up to 30 Cookies Chrome and Safari have no hard limit When you set a cookie after the limit of a single domain name is exceeded, the browser clears the previously set cookies. IE and Opera will clean the least recently used cookies, FF will clean the cookies randomly;

  • The length of each Cookie cannot exceed 4KB

Cookie Security

What kind of security problems Cookie faces, common XSS, CSRF and so on start below.

XSS and defense XSS

If HttpOnly=true is not Set for set-cookie on the server side, the browser side can read and modify the Cookie values via document. Cookie, which is very safe and can cause XSS. Set HttpOnly=true when there is critical information in the Cookie.

Prevent man-in-the-middle hijacking and man-in-the-middle hijacking

The rough distribution is as follows:

DNS <-----> User middle man extranet <-----> HTTPCopy the code

When using HTTPS and purchasing a formal CA certificate, even if the middleman hijacking cannot be decrypted. When set-cookie is Set to Secure=true, the Cookie is sent to the server only through the request encrypted by HTTPS.

CSRF and CSRF defense

CSRF: Cross-site request forgery (CSRF) is an attack that impersonates a trusted user to send an unexpected request to a server.

For example, these unexpected requests might be done by adding malicious parameters to the URL after a jump link:

<img src="https://www.example.com/index.php?action=delete&id=123">
Copy the code

For users with access to https://www.example.com, the tag does this to https://www.example.com without them even noticing, Even if the label is not in https://www.example.com at all.

SameSite cookies prevent cross-site request forgery attacks (CSRF) by allowing the server to request that a Cookie not be sent during a cross-site request. But the SameSite Cookie is still experimental and not supported by all browsers.

  • strict: the browser does not carry it in any cross-domain requestCookieThis can be an effective defenseCSRFHowever, when a website with multiple subdomain names uses the main domain name to store user login information, users need to re-log in to each subdomain name, resulting in poor user experience.
  • laxIn comparison with:strictThis allows you to use it when jumping from a third party siteCookie.

Other defensive

  • Set up thecookieExpiry date
  • To preventcookieIf it is plaintext, the server generates key authentication
  • Generate random sumcookieSend to the server
  • Flash programming security, reviewThe flash codeTry not to use itflashUse the latest videovedio + https + socketOr animation

To the causes, functions, characteristics/disadvantages, security issues of this cookie.

Session

What is session? Session is a mechanism for recording client status. Unlike cookies, which are stored in the browser of the client, Session is stored on the server. Storing sensitive data in client-side cookies is avoided.

The Session mechanism

Session literally means a Session. Who talks to whom? It’s actually a series of interactions between the client browser and the server called a Session.

Create Session (Java)

  1. SessionCreated during the running of the server-side program, different language implementation of the application is created differentlySessionThe method inJavaIs by callingHttpServletRequestthegetSessionMethod, which takes true as an argument. createSessionAt the same time, the server will be for theSessionGenerate uniquesession idthesession idIt is used in subsequent requests to retrieve what has been createdSession.
  2. SessionOnce created, it can be calledSessionRelated methods toSessionAdded content, and these content will only be saved in the server, sent to the client onlysession id
  3. When the client sends the request again, it will send thissession idOnce the request is received, the server will rely on itsession idFind the correspondingSessionTo be used againSession.

The lifetime of the Session

The Session is stored on the server side. For higher access speed, servers typically hold sessions in memory. Each user will have a separate Session. If the Session content is too complex, it can cause memory overflow when a large number of clients access the server. Therefore, the information in the Session should be as minimal as possible.

A Session is automatically created when a user accesses the server for the first time. Note that a Session is created only when accessing programs such as JSPS and servlets, but not when accessing static resources such as HTML and IMAGE. If a Session has not already been generated, you can also use request.getSession(true) to force a Session to be generated.

After a Session is generated, the server updates the last access time of the Session and maintains the Session as long as the user continues to access the Session. Each time a user accesses the server, regardless of whether the user reads or writes a Session, the server considers that the user’s Session is “active”.

Session validity period

As more and more users access the server, more and more sessions are created. To prevent memory overflow, the server removes sessions that have not been active for a long time from memory. This time is the Session timeout. If the server is not accessed after the timeout period, the Session is automatically invalidated.

The Session timeout period is maxInactiveInterval. You can obtain the value from getMaxInactiveInterval() and change it from setMaxInactiveInterval(longInterval).

Session timeout can also be changed in web.xml. Alternatively, you can invalidate a Session by calling its invalidate() method.

There are three ways to invalidate a Session:

  • The server unexpectedly shuts down. (The session will be saved in the session.ser file of the server (in the work folder) when the server is shut down.)
  • The session to commit suicide: callsession.invalidate()Method can kill instantlysession;
  • It can be on the serverweb.xmlIn the file<session-timeout> 30 </session-timeout>Change this to the default value (default 30 minutes) in minutes.

Does the session expire when the browser closes?

A couple of years ago when I was looking at a lot of stuff on the Internet some people would say that sessions expire when the browser closes. Why does it fail? How do you keep it from failing?

Why does it fail?

Here’s why sessions expire when the browser is closed, but it’s not exactly true:

  1. Generated on the server sidesessionAnd thesessionidthroughset-cookieSend it to the browser
  2. In the future, every request except picture, static file request, other requests will be broughtThe service sideWrite to the browsercookie
  3. The service sideTo receivesessionidThrough thesessionidFind the correspondingsessioninformation
  4. Set in the current domain name when the browser is closedcookieWill be empty
  5. The next request is received by the serversessionfornullThe server considers the current user to be a new user and logs in again or directly sets a new usersessionid

That’s why sessions expire when the browser closes.

How do you keep it from failing?

Expries or max-age is Set in set-cookie, which is the expiration time of the Cookie. Or store the Sessionid locally.

web Storage

The Web Storage API provides mechanisms for browsers to store key/value pairs in a more intuitive way than using cookies.

Web Storage has the following two mechanisms:

  • sessionStorageFor each given Origin, a separate storage area is maintained that is available for the duration of the page session (that is, as long as the browser is open, including page reloads and resumes).
  • localStorageSame functionality, but data remains after the browser closes and then opens again.

Note that whether the data is stored in localStorage or sessionStorage, they are specific to the protocol of the page.

localStorage

The read-only localStorage property allows you to access a Document source (Origin) object Storage; The stored data is saved in the browser session. Data stored in localStorage can be retained for a long time.

sessionStorage

The sessionStorage property allows you to access a sessionStorage object. Data stored in sessionStorage is cleared at the end of the page session. The page session remains as long as the browser is open, and the original page session remains when the page is reloaded or restored. Opening a page with a new TAB or window initializes a new session in the top-level browsing context, unlike session cookies.

LocalStorage is different from sessionStorage

Data stored in localStorage can be retained for a long time, while data stored in sessionStorage is cleared when the page session ends.

conclusion

The difference between session and cookie:

  • sessionStored on the server,cookieStored in the client
  • sessionthancookieIt’s safer becausesessionStored on the server
  • sessionIs a data structure stored on the server to track user status. this data can be stored in clusters, databases, files.
  • cookieIs a mechanism for the client to save user information, used to record some information about the user, is also implementedsessionIs a way of.

The difference between Web storage and cookies:

  • web storagesandcookieIs different in its role,web storageIs used for local mass storage of data (web storageStorage up to 5MB); whilecookieIs used for information transfer between the client and the server;
  • web storageThere aresetItem,getItem,removeItem,clearWait for a method,cookieWe need to encapsulate it ourselvessetCookie,getCookie,removeCookie

reference

HTTP cookies

Web Storage API

Window.localStorage

Window.sessionStorage

I’ll get cookie straight for you this time!

Understand the difference between Session and Cookie in depth

A Detailed explanation of the operation mechanism of Cookie and Session (Part I)

Good job interview! This is the real difference between cookies, sessions and tokens