Cookies, Session

A 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

A Session represents a Session between a server and a client. The Session object stores properties and configuration information required by a specific user’s Session. This way, variables stored in the Session object will not be lost when the user jumps between Web pages of the application, but will persist throughout the user Session. When the client closes the Session or the Session times out, the Session ends

What’s the difference between cookies and sessions?

  • The Cookie is stored on the client (browser) and the Session is stored on the server.
  • Different access methods: Cookie can only save ASCII, Session can store any data type, generally we can keep some commonly used variable information in Session, such as UserId.
  • Different validity periods: Cookies can be set to hold for a long time. For example, the default login function that we often use, the Session generally has a short expiration time and will be invalid if the client is closed or the Session times out.
  • The privacy policies are different: Cookies are stored on the client, which is easy to be obtained illegally. In the early days, some people stored users’ login names and passwords in cookies, resulting in information theft. Session is stored on the server and is more secure than cookies.
  • The storage size is different. The data saved by a single Cookie cannot exceed 4K. The Session can store much more data than cookies.

Cookie

The cookie mechanism

  • Session Cookie: The Session Cookie is the simplest Cookie. It does not need to specify an expiration date or max-age. It is only valid during the Session and is automatically deleted after the browser closes.
  • Permanent Cookie: Unlike session cookies, persistent cookies can specify a specific expiration time (Expires) or max-age.

The principle of cookies

When visiting the website for the first time, the browser sends a request, and the server responds to the request, it will add a set-cookie option in the response header and put the Cookie in the response request. When the browser sends a request for the second time, it will send the Cookie information to the server through the Cookie request header. The server will identify the user, and the Cookie expiration time, domain, path, expiration date, and applicable site can be specified as required.

Cookie security policy

attribute role
value If used to store user status, the value should be encrypted and plaintext user ids cannot be used
http-only This tells the browser that the Cookie can only be transmitted by the browser Http protocol, and other access methods are prohibited. Cookies cannot be accessed through JS to reduce XSS attacks
secure This parameter can be carried only in HTTPS requests. HTTPS protects cookies from theft and tampering during transmission between the browser and Web server.
same-site Reduce CSRF attacks by stating that browsers cannot carry cookies in cross-domain requests (but with some browser compatibility)
Max-Age Set the cookie expiration time, in seconds
Domain Specifies the domain to which the Cookie belongs

SameSite

  • Strict allows only one party to request with cookies, that is, the browser will only send cookies that are requested by the same site, that is, the current web URL is exactly the same as the requested target URL.
  • Lax allows some third-party requests to carry cookies
  • None sends cookies whether it is cross-site or not

Application Scenarios:

  • Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  • Personalization
  • Browser behavior tracking

Session

The session mechanism

When the server receives a request and needs to create a session object, it first checks whether the client request contains a session ID. If yes, the server returns the corresponding session based on the ID. If no, the server creates a new session object and returns the session ID to the client in the response. Generally, the sessionid is stored to the client in cookie mode, and the browser sends the sessionid to the server according to the rules during the interaction. If the user disables cookies, the URL needs to be rewritten

Application scenario: Saves the special information of each user and distinguishes different users by using the SessionID

  • Shopping cart in online shopping mall
  • Saves the login information of the user
  • Store some public data in a session
  • Prevent unauthorized login

Disadvantages of separation:

Cookies:

  • Limited size
  • Users can disable cookies
  • Low security
  • Some states cannot be saved on the client side
  • Cookies are sent to the server on every access, wasting bandwidth
  • Cookie data has the concept of a path that restricts cookies to a single path (each cookie has a field associated with it, the scope of which is typically specified by the Donmain property. If the domain of the Cookie is the same as the domain of the page, then we call the Cookie a first-party Cookie. If the domain of the Cookie is different from the domain of the page, It is called a third-party Cookie. When a page contains images or resources (such as images) stored in other domains, first-party cookies are also sent only to the server that set them.

The session:

  • The more things a session holds, the more memory it consumes on the server. For a site with many online users, the memory pressure on the server will be high
  • Depends on cookies. If cookies are disabled, URL rewriting is used, which is not secure

– Creating session variables is very arbitrary, can be called at any time, does not require the developer to do precise processing, so overuse of session variables can make the code unreadable and difficult to maintain

If cookies are disabled in the browser, how do you ensure that the whole mechanism works

  • In the first scenario, each request carries a SessionID parameter. You can also submit the request by Post, or you can concatenate XXX after the request address. SessionID=123456… .
  • The second scheme is Token mechanism. The Token mechanism is mainly used for the interaction between the App client and server, and can also be used for user status management on the Web.

Token means “Token” and is a string generated by the server as an identifier for a client to make a request. The Token mechanism is similar to the Cookie and Session mechanism.

Distributed Session

In order to support more traffic, the backend often requires multiple servers to jointly support user requests from the front-end. Therefore, if A user logs in on server A, the second request on server B will result in login failure

Distributed sessions generally have the following solutions:

  • Nginx IP_hash policy. The server uses the Nginx proxy, and each request is allocated according to the hash of the access IP address. In this way, the requests from the same IP address can access the same background server, avoiding the problem that A Session is created on server A and sent to server B for the second time.

  • Session replication: When a Session changes on any server, the node serializes all the contents of that Session and broadcasts them to all other nodes.

  • Shared Session, stateless phone on the server, the user’s Session information is centrally managed by the cache middleware to ensure that the response results distributed to each server are consistent.

Token

Token Means that the server sends the user information encoded by Base64Url to the client. Each time a user requests this information, the server can decrypt the information and know who the user is. This method is called JWT(Json Web Token).

  1. A user sends requests using a user name and password
  2. Program verification
  3. The program returns a signed token to the client
  4. The client stores tokens and sends requests each time
  5. The server validates the Token and returns data

The advantage of Token compared with Session is that when multiple back-end systems are deployed, the client directly carries data when accessing the Token. Therefore, data sharing is not required.

Advantages:

  1. Brevity: It can be sent via a URL,POST parameter, or HTTP header parameter, because data is small and fast
  2. Self-contained: Because the string contains the information the user needs, multiple queries to the database are avoided
  3. Because tokens are stored on the client side as Json, JWT is cross-language
  4. There is no need to save session information on the server, especially for distributed micro services

JWT – JSON Web Token

JSON Web Tokens by dot (.) The three parts of the partition are:

  1. Header
  2. Payload
  3. Signature (= Signature)

Therefore, JWT is usually presented as follows:

xxxxx.yyyyy.zzzz

Header

Header is a JSON object

{
  "alg": "HS256".// Indicates the signature algorithm, the default is HMAC SHA256 (HS256)
  "typ": "JWT"  // Indicates the type of the Token. JWT Token is written as JWT
}
Copy the code

Payload

The Payload part is also a JSON object that stores the data that needs to be transmitted

{
  // 7 official fields
  "iss": "a.com".// Issuer: indicates the issuer
  "exp": "1d".// Expiration time: expiration time
  "sub": "test"./ / the subject: theme
  "aud": "xxx".// Audience
  "nbf": "xxx".// Not Before: effective time
  "iat": "xxx".// Issued At: time of issuance
  "jti": "1111".// JWT ID: ID
  // Private fields can be defined
  "name": "John Doe"."admin": true
}
Copy the code

JWT is unencrypted by default and anyone can read it, so don’t put secret information in this section.

Signature (= Signature)

Signature is a Signature to the first two parts, preventing data from being tampered with.

First, you need to specify a secret. This key is known only to the server and cannot be disclosed to users. Then, using the signature algorithm specified in the Header (HMAC SHA256 by default), generate the signature as follows.

HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Copy the code

After calculating the Signature, add the Header, Payload, and Signature parts into a string, and use dots (.) between each part. Delimit, and it can be returned to the user.

JWT = Base64(Header) + "." + Base64(Payload) + "." + $Signature
Copy the code

How to Stay Safe

  • Send JWT using HTTPS; Do not write secret data to JWT when sending without HTTPS
  • Expire time must be set in the payload of the JWT

use

The client receives the JWT returned by the server, which can be stored in cookies or localStorage. Thereafter, the client takes this JWT with it every time it communicates with the server. You can put it in a Cookie and send it automatically, but that’s not cross-domain, so it’s better to put it in the HTTP request header Authorization field.

Authorization: Bearer <token>
Copy the code

Alternatively, the JWT is placed in the data body of the POST request when it is cross-domain.

The role of JWT

JWT was originally intended to achieve authorization and identity authentication, which can achieve stateless and distributed Authorization of Web applications. The general implementation process is as follows

  1. The client needs to bring the user name/password and other identifiable content to the authorization server to obtain JWT information;
  2. Each service carries the Token content and interacts with the Web server. The service server verifies whether the Token is a valid Token issued by authorization and whether the current service request is valid.

Note: It is not recommended to apply for a Token for each request except for security requirements, because it will increase service time. Apply only when you log in, and then use the expiration date of the JWT or other means to ensure that the JWT is valid;

WebStorage

LocalStorage and sessionStorage

  1. The life cycle

The life cycle of localS is permanent, and data does not disappear when the page or browser is closed, unless manual clearing of the data sessionS life cycle is only valid for the current session and only exists in the current browser window, which is destroyed when closed

  1. Storage size: the storage size of localStorage and sessionStorage is generally 5M

  2. Storage location: All storage is stored on the client and does not interact with the server

  3. Store content types: Both can only store string types, which can be handled with JSON object stringify and Parse for complex objects

  4. Application Scenarios:

“LocalS” : used for long-term login (to determine whether a user has logged in), which is suitable for long-term local saving of data sessionS: sensitive account for one-time login

features cookie localStorage sessionStorage indexDB
Data life cycle Generally generated by the server can set the expiration time Unless it’s cleaned up, it’s always there Clear the page after closing Unless it’s cleaned up, it’s always there
Data store size 4K 5M 5M infinite
Communicates with the server Each time it is carried in the header, it has an impact on request performance Don’t participate in Don’t participate in Don’t participate in

reference

  • Same origin Policy Reference article
  • Cookie, Session, Token