The difference and usage of Session, Cookie, Token

The organization context of this article is as follows

Cookie 和 Session

The HTTP protocol is a type 无状态协议, that is, every time the server receives a client's request, 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 for the stateless nature of HTTP.

What is Session

The client requests the server, and the server will open a block for this request 内存空间. This object is the Session object, and the storage structure is  ConcurrentHashMap. Session makes up for the stateless nature of HTTP. The server can use Session to store some operation records of the client during the same session.

How to determine whether the Session is the same session

When the server receives the request for the first time, it opens up a Session space (creates a Session object), and generates a sessionId at the same time, and sends a response requesting cookie setting to the client through the Set-Cookie: JSESSIONID=XXXXXXX command in the response header; After the client receives the response, it sets a cookie with JSESSIONID=XXXXXXX on the local client. The expiration time of the cookie is the end of the browser session.

Next, every 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 to get the value of JSESSIONID. The requested sessionId.

Disadvantages of Session

The Session mechanism has a shortcoming. For example, server A stores Session, that is, after load balancing, if A's access volume increases sharply for a period of time, it will be forwarded to B for access, but Server B does not store A's Session, which will lead to Session ’S failure.

What are cookies

Cookie HTTP protocol comprises  Web Cookie and 浏览器 Cookie, the server sends it to the Web browser of a small blocks of data. The cookie sent by the server to the browser will be stored by the browser and sent to the server together with the next request. Usually, it is used to determine whether two requests are from the same browser, for example, the user remains logged in.

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

Cookies are mainly used for the following three purposes

  • 会话管理

Login, shopping cart, game score, or other things the server should remember

  • 个性化

User preferences, themes or other settings

  • 追踪

Record 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 reduce performance (especially for mobile data connections).

Create 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 and the HTTP header are combined to send a request to the server.

Set-Cookie and Cookie header

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

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.

There are two types of cookies, one is Session Cookies and the other is Persistent Cookies. If the cookie does not contain an expiration date, it will be regarded as a session cookie. The session cookie is stored in the memory and will never be written to disk. When the browser is closed, the cookie will be permanently lost thereafter. If the cookie contains 有效期 , it will be treated as a persistent cookie. On the expiry date specified, the cookie will be deleted from the disk.

There is another one Cookie的 Secure 和 HttpOnly 标记, let’s introduce one by one  below

Session Cookies

The above example creates a session cookie. The session cookie has a feature. The cookie will be deleted when the client is closed because it has no designation Expiresor  Max-Age instruction.

However, web browsers may use session restoration, which makes most session cookies permanent, as if the browser has never been closed.

Persistent Cookies

Persistent cookies will not expire when the client is closed, but will expire on 特定日期(Expires)or 特定时间长度(Max-Age)outside. E.g

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;

Cookie's Secure and HttpOnly tags

The secure cookie needs to be sent to the server in an encrypted manner through the HTTPS protocol. Even if it is secure, 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 an attacker to obtain the user's cookie information through programs (JS script, Applet, etc.), causing the user's cookie information to be leaked and increasing the attacker's threat of cross-site scripting attacks.

  • HttpOnly is Microsoft's extension to Cookie. This value specifies whether the Cookie can be accessed through client-side scripts.

  • If the HttpOnly attribute is not set to true in the Cookie, the Cookie may be stolen. Stolen cookies can contain sensitive information that identifies site users, such as ASP.NET session IDs or Forms authentication tickets. Attackers can replay the stolen cookies to pretend to be users or obtain sensitive information, conduct cross-site scripting attacks, etc.

Scope of cookies

Domain And the  Path logo defines the scope of the cookie: which URL the cookie should be sent to.

Domain The identifier specifies which hosts can accept cookies. If not specified, it will default to the current host ( not including subdomains ). If specified Domain, it generally contains the subdomain name.

For example, if set  Domain=mozilla.org, the cookie is also included in the subdomain (eg developer.mozilla.org).

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

  • /docs

  • /docs/Web/

  • /docs/Web/HTTP

Comparison of JSON Web Token and Session Cookies

JSON Web Token ,简称 JWT, It and both  Sessioncan provide user authentication for the website, but they are not the same thing.

The following is a study of the difference 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 to enter a different page and after logging in to a website or application.

If you don't have these two, then you may need to log in every page switch. 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 内存中will not remember your previous actions.

Therefore, if you log in and visit another page that you have permission to access, since HTTP does not record the information you just logged in, you will log in again.

JWT and Session Cookies are 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 every time a new request is made.

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

What are Session Cookies

Session Cookies are also called 会话 Cookies, in Session Cookies, the user's login status will be saved in 服务器the 内存middle. When the user logs in, the session is safely created by the server.

At each request, the server will read the SessionId from the session cookie. If the data on the server is the same as the read SessionId, the server will send a response to the browser to allow the user to log in.

What is Json Web Tokens

The abbreviation of Json Web Token is JWT, which can usually be called  Json 令牌. It is RFC 7519 defined 安全的as Json 对象a form of information  transmission. The information stored in the JWT is passed 数字签名, so it can be trusted and understood. You can use the HMAC algorithm or use the RSA/ECDSA public/private key to sign the JWT.

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

  • 认证(Authorization): This is the most common case of using JWT. Once the user logs in, each subsequent request will contain the JWT, allowing the user to access the routes, services, and resources allowed by the token. 单点登录It is a feature of JWT that is widely used today because of its small overhead.

  • 信息交换(Information Exchange): JWT is a way to safely transmit information. The JWT is signed and authenticated by using the public key/private key. In addition, since the signature is used  head and  payload calculated, you can also verify whether the content has been tampered with.

JWT format

Below, we will discuss what the composition and format of JWT are

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

  • Header

  • Payload

  • Signature

Therefore, a very simple JWT composition would be as follows

Then we discuss the different parts separately.

Header

Header is the header of JWT, it usually consists of two parts: 令牌的类型(即 JWT)and used  签名算法, such as HMAC SHA256 or RSA.

E.g

{
  "alg": "HS256",
  "typ": "JWT"
}

After specifying the type and signature algorithm, the Json block is  Base64Url encoded to form the first part of the JWT.

Payload

The second part of the token is  Payloadthat the Payload contains a statement. A statement is a statement about an entity (usually a user) and other data. There are three types of declarations: registered, public and private  declarations.

  • registered 声明: Contains a set of recommended pre-defined declarations, mainly including

  • public 声明: Public statement, you can add any information, generally add user related information or other necessary information required by the business, but it is not recommended to add sensitive information, because this part can be decrypted on the client.

  • private 声明: Custom declarations, aimed at sharing information between parties who agree to use them, are neither registration declarations nor public declarations.

E.g

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Then 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, this visa information 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)

The signature is used to verify that the message has not changed in the process, and for tokens signed with a private key, it can also verify the true identity of the sender of the JWT

Piece together

Now we put the above three dot-separated Base64-URL string parts together, this string can easily pass these strings in HTML and HTTP environments.

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

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

If you want to test and write by yourself, you can visit the JWT official website https://jwt.io/#debugger-io

    The difference between JWT and Session Cookies

Both JWT and Session Cookies provide secure user authentication, but they are different in the following points

Cryptographic signature

JWT has a cryptographic signature, but Session Cookies does not.

JSON is stateless

JWT Yes 无状态, because the declaration is stored in 客户端, not in server memory.

Authentication may be 本地performed, instead of requesting the server must be a database or the like in position. This means that the user 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 the server memory, which means that if the website or application is large, it will consume a lot of resources. Since JWTs are stateless, in many cases, they can save server resources. Therefore, JWT is stronger than Session Cookies 可扩展性.

JWT supports cross-domain authentication

Session Cookies can only be used in 单个节点的域or 子域valid in it . If they try to access through the third node, they will be banned. This is a problem if you want your website to establish a secure connection with other sites.

Using JWT can solve this problem, using JWT can pass 多个节点user authentication, which is what we often say 跨域认证.

Selection of JWT and Session Cookies

We discussed the difference between JWT and Cookies above, I believe you will also have a deeper understanding of the selection, roughly 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 enterprise-level sites, applications or nearby sites, and need to handle a large number of requests, especially third parties or many third parties (including APIs in different domains), JWT is obviously more suitable.

postscript

I asked this question during the interview two days ago, so I wrote an article to summarize, and I also asked an interview question, disabling Cookies, how to use Session  ? I checked it on Baidu and found that this is a PHP interview question, em.....

But I still choose to understand how to use Session after disabling Cookies

  • If Cookies are disabled, the server will still send the sessionId to the browser in the form of a cookie, but the browser will no longer save this cookie (ie sessionId).

  • If you want to continue using session, you need to use  URL 重写 the method to achieve it, you can refer to https://www.cnblogs.com/Renyi-Fan/p/11012086.html

Related references:

https://www.cnblogs.com/Renyi-Fan/p/11012086.html

https://blog.csdn.net/qq_28296925/article/details/80921585

https://www.cnblogs.com/-ROCKS/p/6108556.html

https://www.allaboutcookies.org/manage-cookies/

https://www.jianshu.com/p/4a124a10fcaf

https://tools.ietf.org/html/rfc7519

https://jwt.io/introduction/

https://wp-rocket.me/blog/browser-cache-vs-cookies-difference/

https://wp-rocket.me/blog/difference-json-web-tokens-vs-session-cookies/

Guess you like

Origin blog.csdn.net/qq_39331713/article/details/105369509