Want to talk to the interviewer? After reading this Session, Cookie, Token you will have no problem

Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem

Cookie and Session
HTTP protocol is a stateless protocol, that is, each time the server receives a request from the client, it is a brand-new request, and the server does not know the client's historical request record; the main purpose of Session and Cookie is to make up The stateless nature of HTTP.

Session is what the
client requests the server. The server will open up a memory space for this request. This object is the Session object, and the storage structure is ConcurrentHashMap. Session makes up for the stateless nature of HTTP, and the server can use Session to store the client's operation records during the same session.

How does Session determine whether the same session
server receives the request for the first time, opens up a session space (creates a Session object), and generates a sessionId at the same time, and sends the client-side Set-Cookie: JSESSIONID = XXXXXXX command to the client Send a response requesting the setting of a cookie; after receiving the response, the client sets a cookie message with JSESSIONID = XXXXXXX on the local client , and the expiration time of the cookie is the end of the browser session;

Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
Next, each time the client sends a request to the same website, the request header will carry the cookie information (including sessionId). Then, the server reads the cookie information in the request header and obtains the value named JSESSIONID. The requested sessionId.

Disadvantages of
Session The Session mechanism has a disadvantage. For example, the A server stores the Session, that is, after load balancing, if A's access volume surges over a period of time, it will be forwarded to B for access, but the B server does not store the A ’s Session. Will lead to the failure of Session.

What are cookies? Cookies in the Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
HTTP protocol include Web cookies and browser cookies. It is a small piece of data sent by a server to a web browser. The cookie sent by the server to the browser, the browser will store it and send it to the server along with the next request. Usually, it is used to judge whether two requests come from the same browser, for example, the user stays logged in.

The HTTP Cookie mechanism is a supplement and improvement of the stateless HTTP protocol

Cookies are mainly used for the following three purposes

Session management
login, shopping cart, game score, or other things the server should remember

Personalize
user preferences, themes or other settings

Track
records and analyze user behavior

Cookies were once used for general client storage. Although this is legal because they are the only way to store data on the client, it is now recommended to use modern storage APIs. Cookies are sent with every request, so they may degrade performance (especially for mobile data connections).

Creating a Cookie
When receiving an HTTP request from a client, the server can send a Set-Cookie header with a response. The cookie is usually stored by the browser, and then the cookie is sent to the server along with the HTTP header.

Set-Cookie and Cookie header The
Set-Cookie HTTP response header sends cookies from the server to the user agent. Here is an example of sending cookies

Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
This header tells the client to store cookies

Now, with each new request to the server, the browser will use the Cookie header to send all previously stored cookies back to the server. Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
There are two types of cookies, one is Session Cookies and the other is Persistent Cookies. If a cookie does not contain an expiration date, it is considered a session cookie. Session cookies are stored in memory and will never be written to disk. When the browser is closed, the cookies will be permanently lost thereafter. If a cookie contains an expiration date, it is considered a persistent cookie. Cookies will be deleted from the disk on the date specified by the expiration date.

There is also the Secure and HttpOnly tags for cookies, which are introduced in order below

Session Cookies The
above example creates session cookies. Session cookies have a characteristic. Cookies are deleted when the client is closed because it does not specify Expires or Max-Age instructions.

However, web browsers may use session restore, which keeps most session cookies permanent, as if the browser had never been closed.

Permanent Cookies
Permanent cookies do not expire when the client is closed, but expire on a specific date (Expires) or a specific length of time (Max-Age). For example, Set-Cookie: id = a3fWa; Expires = Wed, 21 Oct 2015 07:28:00 GMT;
Copy the code of
Cookie Secure and HttpOnly marked
secure cookies need to be sent to the server through HTTPS protocol through encryption. Even if it is safe, sensitive information should not be stored in cookies because they are inherently insecure and this flag does not provide real protection.

The role of HttpOnly

The lack of the HttpOnly attribute in the session cookie will cause the *** to obtain the user's cookie information through the program (JS script, Applet, etc.), resulting in the leakage of the user's cookie information, increasing the *** threat of cross-site scripting.
HttpOnly is an extension made by Microsoft to cookies. This value specifies whether cookies can be accessed through client scripts.
If the HttpOnly attribute is not set to true in the cookie, the cookie may be stolen. The stolen cookies can contain sensitive information that identifies users of the site, such as ASP.NET session IDs or Forms authentication tickets. *** The person can replay the stolen cookies in order to pretend to be users or obtain sensitive information for cross-site scripting Wait.
The
domain and path identifiers of the cookie define the scope of the cookie: the URL to which the cookie should be sent.

The Domain ID specifies which hosts can accept cookies. If not specified, the default is the current host (without subdomains). If Domain is specified, it generally contains subdomain names.

For example, if you set Domain = mozilla.org, cookies are also included in subdomains (such as developer.mozilla.org).

For example, if you
set Path = / docs, the following addresses will match:

/ docs
/ docs / Web /
/ docs / Web / HTTP
Comparison of JSON Web Token and Session Cookies
JSON Web Token, abbreviated as JWT, both it and Session can provide user authentication for the website, but they are not the same thing.

The following is a study of the differences between JWT and Session

Similarities
between JWT and Session Cookies Before discussing JWT and Session Cookies, it is necessary to understand their similarities.

They can be used to authenticate users, and they can also be used to authenticate users when they click on different pages and after logging in to websites or applications.

If you do n’t have both, then you may need to log in every time you switch between pages. Because HTTP is a stateless protocol. This means that when you visit a web page and then click another page on the same site, the server ’s memory will not remember your previous operation.

Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
Therefore, if you log in and visit another page that you have access to, because HTTP will not record the information you just logged in, you will log in again.

JWT and Session Cookies are mechanisms used to handle switching between different pages and save user login information.

In other words, these two technologies are used to save your login status, allowing you to browse any password-protected website. This problem is solved by authenticating user data each time a new request is generated.

So what are the similarities between JWT and Session Cookies? That is, they can support you to record and verify your login status between sending different requests.

What is Session Cookies
Session Cookies are also called session cookies. In Session Cookies, the user's login status is saved in the server's memory. When the user logs in, the session is created securely by the server.

On every request, the server reads the SessionId from the session cookie. If the server-side data and the read SessionId are the same, the server sends a response to the browser, allowing the user to log in.
Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
What is Json Web Tokens?
The abbreviation of Json Web Token is JWT, which can usually be called Json token. It is a form defined in RFC 7519 for the secure transmission of information as Json objects. The information stored in JWT is digitally signed, so it can be trusted and understood. JWT can be signed using HMAC algorithm or RSA / ECDSA public / private key.

The use of JWT is mainly used for the following two points

Authentication (Authorization): This is the most common case of using JWT. Once the user logs in, each subsequent request will include JWT, allowing the user to access the routes, services and resources allowed by the token. Single sign-on is a feature of JWT that is widely used today because of its low overhead.
Information Exchange: JWT is a way to transfer information securely. Sign and authenticate JWT by using public / private keys. In addition, because the signature is calculated using head and payload, you can also verify whether the content has been tampered with.
JWT format
Below, we will discuss the composition and format of JWT

JWT is mainly composed of three parts, each part is divided by. Each part is

Header
Payload
Signature
Therefore, a very simple JWT composition would be as follows

Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
Then we discuss the different parts separately.

Header

Header is the header of JWT, it usually consists of two parts: the type of token (ie JWT) and the signature algorithm used, such as HMAC SHA256 or RSA.

E.g

{
"alg": "HS256",
"typ": "JWT"
} After
copying the code to
specify the type and signature algorithm, the Json block is encoded by Base64Url to form the first part of JWT.

Payload

The second part of Token is Payload, which contains a statement. Statements are statements about entities (usually users) and other data. There are three types of declarations: registered, public and private declarations.

Registered statement: Contains a set of recommended pre-defined statements, mainly including
ISS issuer iss (issuer) issuer exp (expiration time) expiration time sub (subject) subject aud (audience) audience nbf (Not Before) effective time iat ( Issued At) issue time jti (JWT ID) number

Public statement: Public statement, you can add any information, generally add user related information or other business necessary information, but it is not recommended to add sensitive information, because this part can be decrypted at the client.
Private statement: A custom statement designed to share information between parties who agree to use them, neither a registration statement nor a public statement.
E.g

{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Copy the code
and the payload Json block will be Base64Url encoded to form the second part of the JWT.

signature

The third part of JWT is a visa information, which consists of three parts

header (after base64)
payload (after base64)
secret For
example, we need HMAC SHA256 algorithm to sign

HMACSHA256 (
base64UrlEncode (header) + "." +
Base64UrlEncode (payload),
secret)
Copy the code
signature to verify that the message has not changed in this process, and for the token signed with the private key, it can also verify the sending of JWT True identity


Putting it all together Now let's put together the three Base64-URL string parts separated by dots. This string can easily pass these strings in HTML and HTTP environments.

Here is a complete JWT example, which encodes the header and payload, and then uses the signature to sign

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
copy the code
Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem
if you want to write your own test, you can visit the official website jwt.io/#debugger-i... JWT

Differences between
JWT and Session Cookies Both JWT and Session Cookies provide secure user authentication, but they have the following differences

The cryptographic signature
JWT has an encrypted signature, while Session Cookies do not.

JSON is stateless.
JWT is stateless because the declaration is stored in the client, not in the server memory.

Authentication can be done locally, rather than when the request must go through a server database or similar location. This means that users can be authenticated multiple times without having to communicate with the database of the site or application, and without consuming a lot of resources in the process.

Scalability
Session Cookies are stored in server memory, which means that if the website or application is very large, it will consume a lot of resources. Because JWTs are stateless, they can save server resources in many cases. Therefore, JWT is more scalable than Session Cookies.

JWT supports cross-domain authentication
Session Cookies can only be used in a single node's domain or its sub-domain. If they try to access through the third node, they will be banned. This is a problem if you want your site to establish a secure connection with other sites.

Using JWT can solve this problem, using JWT can carry out user authentication through multiple nodes, which is what we often say cross-domain authentication.

Selection of JWT and Session Cookies
We discussed the difference between JWT and Cookies above, I believe you will have a deeper understanding of the selection, generally speaking

For small and medium-sized websites that only need to log in users and access some information stored in the site database, Session Cookies are usually sufficient.

If you have an enterprise-level site, an application or a nearby site, and need to handle a large number of requests, especially third parties or many third parties (including APIs located in different domains), then JWT is obviously more suitable.

The postscript
asked this question during the interview two days ago, so I wrote an article to summarize, and also asked an interview question, disable Cookies, how to use Session? I checked Baidu online and found that this is an interview question for PHP ...Want to talk to the interviewer?  After reading this Session, Cookie, Token you will have no problem

But still choose to understand, how to disable Cookies, use Session

If cookies are disabled, the server will still send the sessionId to the browser as a cookie, but the browser no longer saves this cookie (that is, sessionId).
If you want to continue to use the session, you need to use URL rewriting to achieve, you can refer to www.cnblogs.com/Renyi-Fan/p...Related
reference:

www.cnblogs.com/Renyi-Fan/p…

blog.csdn.net/qq_28296925…

www.cnblogs.com/-ROCKS/p/61…

www.allaboutcookies.org/manage-cook…

www.jianshu.com/p/4a124a10f…

tools.ietf.org/html/rfc751…

jwt.io/introductio…

wp-rocket.me/blog/browse…

wp-rocket.me/blog/differ…

Guess you like

Origin blog.51cto.com/14783151/2487914