Browser cache, local storage, Cookie, Session, Token

Table of contents

Front-end communication (rendering, http, cache, asynchronous, cross-domain)

HTTP and HTTPS, HTTP version, status code

request header, response header

cache

Force caching: Cache-Control:max-age (HTTP1.1)>Expires (1.0)

Set strong cache for static resources such as js, css, img, and public resources of third-party libraries

Negotiate cache

If-Modified-Since/Last-Modified

If-None-Match/ETag: Server-generated resource identifier (hash/entity tag)

html resource settings negotiation cache

Storage: js/image (memory, refresh), css (hard disk, rendering)

Storage comparison

local storage

Cookie: stores key-value pairs

Introduction: http stateless

Classification

Session cookie (default): client memory

Persistent Cookie: on the client’s hard drive (txt)

Attributes

Required: Name, Value

Scope

Domain: Domain name or IP (scope, cannot cross domain, has nothing to do with port), the default is the current domain name

Sharing between first-level domain names and second-level domain names is allowed

Path (default '/'): Specifies which route the cookie will take effect under

safety

HttpOnly (not set by default): When true, only http can be read and js cannot be read, preventing malicious scripts from attacking through cookies.

However, the cookie can be modified manually in Application, so there is still no way to prevent XSS attacks.

Secure (default false): true means that only https requests can be carried

SameSite (not set by default): Restricts whether third-party URLs can carry cookies (new in Chrome51, mandatory in chrome80+)

Strict: Only cookies that are requested with the same site are allowed to be sent

Lax (default): Send the cookie in top-level navigation and POST requests, but not in cross-site GET requests

None: Send cookies arbitrarily, but need to set Secure at the same time, that is, https must be used

Memory optimization

Max-Age>Expires

Priority (not set by default): priority

Chrome: Low/Medium/High. When the number of cookies is exceeded, the low ones will be cleared first.

js operation cookie

Read/modify document.cookie: When HttpOnly is true, only http can be read, js cannot be read.

set public /index.html /script 

Delete: expires=new Date(0)

cross domain request

Set cookies on the server: SameSite=None (send cookies arbitrarily) Secure=true (https)

Response header Access-Control-Allow-Credentials=true (allow sending Credentials)

Request header withCredentials=true (Credentials will be sent)

WebStorage: stores key-value pairs locally and does not participate in server communication.

localStorage

Application: to store information about tabs and restore sessions

sessionStorage

IndexDB (non-relational database running in the browser)

Ways to implement authorization: cookie, session, token, OAuth

Authentication: authenticating users

Authorization: Authorize third-party applications

Credentials: Mark the identity of the visitor

Token

Access Token: Resource credentials required to access the resource interface (API)

Authentication process of token ​Edit​Refresh Token: Refresh the token of access token

The difference between Token and Session

storage

Safety

application

refresh

Hard refresh: ignore cache and request again

Normal loading: cache


Front-end communication (rendering, http, cache, asynchronous, cross-domain)

HTTP and HTTPS, HTTP version, status code

request header, response header

cache

Force caching: Cache-Control:max-age (HTTP1.1) >Expires(1.0

Expires:Mon, 29 Jun 2020 11:10:23 GMT

"The server's time and the browser's time may not be consistent ," so HTTP1.1 proposes a new field to replace it.

Common Cache-Control directive values ​​and their meanings:

  1. public: Indicates that the response can be stored by any cache (including clients and proxy servers).

  2. private: indicates that the response can only be cached by the client and should not be cached by the proxy server.

  3. no-cache: requires the cache server to verify the validity of the response before returning it. Even if the cache has a valid copy, the request will be sent to the original server for verification.

  4. no-store: Indicates that neither the request nor the response should be cached and all content must be re-fetched from the server.

  5. max-age=<seconds>: Specifies the maximum time that the response can be cached, in seconds.

Set strong cache for static resources such as js, css, img, and public resources of third-party libraries

Requests with a gray status code represent the use of forced caching , and the Size value corresponding to the request represents the location where the cache is stored, which are from memory cache and from disk cache respectively.

  • The order in which the browser reads the cache is memory –> disk.
  • Visit URL–> 200 –> Close tab–> Reopen URL–> 200 (from disk cache) –> Refresh–> 200 (from memory cache)

Negotiate cache

If-Modified-Since/Last-Modified

If the last modified date of the resource is Last-Modified <= If-Modified-Since, it will be 304 (Not Modified)

If-None-Match/ETag : Server-generated resource identifier (hash/entity tag)

If this header is used, it is a conditional request. If the request identifier == the current identifier of the resource, then 304

If-None-Match: "d41d8cd98f00b204e9800998ecf8427e"

A conditional request means that the client attaches some conditions when initiating the request, so that the server can decide whether to return the actual response content based on these conditions.

It can be understood as if in the code. The input is determined, but the output varies according to the actual situation.

html resource settings negotiation cache

Storage: js/image (memory, refresh), css (hard disk, rendering)

Storage comparison

cookie session
relation Record the status of http request Create a session cookie for the first session
storage location
Client memory (session)/hard disk (persistent)
Server
size Generally, the data size saved by a single cookie does not exceed 4kb. Unlimited
quantity A single domain name can save up to 30 cookies (depending on browsers) Unlimited
value storage format string object

local storage

Cookie: stores key-value pairs

Introduction: http stateless

Classification

Session Cookie (Default): client memory

Because it is stored in memory, refreshing will not change (keep the connection but re-request), but reopening the browser will change the id

Max-Age: Expiration time (unit seconds)

If it is a negative number , the cookie is a temporary cookie and will expire when you close the browser.

If it is 0 , it means delete the cookie. Default is -1 .

Sort from low to high

Pass session ID between client and server

The value of the Session Cookie is a unique identifier related to the user's session, usually called Session ID .

Invalid when the user closes the entire browser in private browsing mode ;

Otherwise, the session resumes from the last open tab, causing the browser to retain session information, including the Session Cookie.

Force the server to set an expiration time for the session,

When the time since the client last used the session exceeds this expiration time,

The server thinks that the client has stopped its activities and will delete the session to save storage space

Persistent Cookie: on the client’s hard drive ( txt  )

It will not expire until the lifetime expires or the user directly clicks a button such as " Logout " on the web page to end the session.

  1. Remember logged-in status: When a user selects "Remember Me" or a similar option, a website can use a persistent cookie to automatically log the user in on their next visit without having to re-enter their username and password.

  2. Personalization: Websites can use persistent cookies to store user preferences and personalization settings, such as language selection, theme options, font size, etc., to maintain a consistent user experience the next time the user visits.

  3. Tracking user behavior: Persistent cookies can be used to track user behavior on the website, such as recording the user's browsing history, shopping cart contents or other information related to the user's personalized experience.

  4. Advertising targeting: In the field of online advertising, persistent cookies can be used to track user interests and behavior to provide a more targeted advertising experience.

  5. Statistical analysis: Websites can use persistent cookies to collect anonymous statistical data for analyzing user behavior, improving website performance and enhancing user experience.

User hard drive

Attributes

Required: Name, Value
Scope
Domain: Domain name or IP (scope, cannot cross domain, has nothing to do with port), the default is the current domain name
Sharing between first-level domain names and second-level domain names is allowed

If it is set to .example.com, then both the subdomains a.example.com and b.example.com can use the cookie of .example.com; vice versa.

Path (default '/'): Specifies which route the cookie will take effect under
safety
HttpOnly (not set by default): When true, only http can be read and js cannot be read, preventing malicious scripts from attacking through cookies.
However, the cookie can be modified manually in Application, so there is still no way to prevent XSS attacks.

Secure ( default false ): true means that only https requests can be carried
SameSite (not set by default) : Restricts whether third-party URLs can carry cookies (new in Chrome51, mandatory in chrome80+)

A site can contain multiple web pages, such as a personal blog

Strict: Only cookies that are requested with the same site are allowed to be sent
Lax (default): Send the cookie in top-level navigation and POST requests, but not in cross-site GET requests

"Top-level navigation" refers to jumping from a URL on one site to a URL on another site , usually by clicking a link or entering a URL .

None: Send cookies arbitrarily, but Secure must be set at the same time , that is, https must be used
Memory optimization
Max-Age>Expires
Priority (not set by default) : Priority
Chrome: Low/Medium/High. When the number of cookies is exceeded, the low ones will be cleared first.

js operation cookie

Read/modify document.cookie: When HttpOnly is true, only http can be read, js cannot be read.
Set  public /index.html /script 
<script>document.cookie = "sso_ticket=ST-xx-cn"</script>
删除:expires=new Date(0)

new Date(0) : January 1, 970 UTC time, 0 represents the starting time of the Unix timestamp

document.cookie = ‘cookieName=; expires=${new Date(0)}; path=/;’;

A basic refresh just re-fetches the data from the local hard drive to the browser

cross domain request

Set cookies on the server: SameSite=None (send cookies arbitrarily) Secure=true (https)
Response header Access-Control-Allow-Credentials=true (allow sending Credentials)
Request header withCredentials=true (Credentials will be sent)

WebStorage:本地存储Key-value pairs do not participate in server communication

localStorage

应用:to store information about the tab and restore the session
localStorage.setItem('uname','zwq')
localStorage.getItem('uname')
localStorage.key(0)
localStorage.removeItem('uname')
localStorage.clear()

sessionStorage

IndexDB( Non-relational database running in the browser )

IndexedDB: Some browsers may use IndexedDB, a more powerful client-side storage solution for storing larger structured data.

Ways to implement authorization: cookie, session, token, OAuth

OAuth (Open Authorization) authorization framework

Authentication: authenticating users

Authentication on the Internet:

  • Login with username and password
  • Mobile phone number to receive verification code

Authorization: Authorize third-party applications

For third-party applications, the user grants the third-party application permission to access certain resources of the user

  • When you install a mobile app, the APP will ask whether permissions are allowed (access to photo albums, geographical location, etc.)
  • When you access the WeChat mini program, when you log in, the mini program will ask whether you are allowed to grant permissions (obtain personal information such as nickname, avatar, region, gender, etc.)

Credentials: Mark the identity of the visitor

The prerequisite for achieving authentication and authorization is the need for a medium (certificate)  to mark the identity of the visitor

When the user logs in successfully, the server will issue a token to the browser used by the user. This token is used to indicate your identity. Each time the browser sends a request, it will bring this token.

Token

Access Token: Resource credentials required to access the resource interface (API)

The composition of a simple token: uid (user's unique identity), time (timestamp of the current time), sign (signature, the first few digits of the token are compressed into a hexadecimal string of a certain length using a hash algorithm)

The calculation time of parsing the token is exchanged for the storage space of the session, thereby reducing the pressure on the server and reducing frequent database queries.

Features:

  • The server is stateless (no need to store tokens) and has good scalability
  • Support mobile devices
  • The token is completely managed by the application, so it can avoid the same origin policy 

Token authentication process  Refresh Token: Refresh access token token

If there is no refresh token, the access token can also be refreshed, but each refresh requires the user to enter the login user name and password, which will be very troublesome.

With the refresh token, this trouble can be reduced. The client directly uses the refresh token to update the access token without requiring the user to perform additional operations.

  • The validity period of the Access Token is relatively short. When the Access Token expires due to expiration, a new Token can be obtained by using the Refresh Token. If the Refresh Token also expires, the user can only log in again .
  • The Refresh Token and expiration time are stored in the server's database and will only be verified when applying for a new Access Token . It will not affect the response time of the business interface and does not need to be kept in memory like the Session to cope with a large number of requests. ask.

The difference between Token and Session

Session is a mechanism that records the session status of the server and client, making the server stateful and able to record session information .

Token is a token , a resource credential required to access the resource interface (API) . Token makes the server stateless and does not store session information.

storage

  • session: server, session cookie client memory
  • token:localstorage/cookie

Safety

  • As an identity authentication Token, the security is better than that of Session, because each request is signed and can prevent monitoring and replay attacks .

application

  • Session: cannot be shared with other websites or third-party apps .
  • Token: Mobile terminal or if your user data may need to be shared with a third party, or allow a third party to call the API interface

 The mobile terminal does not support cookies very well, and sessions need to be implemented based on cookies, so tokens are commonly used on mobile terminals.

refresh

Hard refresh: ignore cache and request again

com/ctrl+R

Normal loading: cache

com/ctr+Shift+R

Guess you like

Origin blog.csdn.net/qq_28838891/article/details/134588976