The Cookie and Session
HTTP is a stateless protocol, that is, every time a server receives a request from a client, it is a new request, and the server does not know the historical request record of the client. The main purpose of sessions and cookies is to compensate for the stateless nature of HTTP.
What is the Session
The client requests the server, and the server allocates a memory space for the request. This object is the Session object, and the storage structure is ConcurrentHashMap. Sessions compensate for the stateless nature of HTTP by allowing the server to store records of the client’s operations during the same Session.
How does Session check whether it is the same Session
When the server receives the request for the first time, it creates a Session space (the Session object is created), generates a sessionId, and passes the ** set-cookie in the response header: JSESSIONID=XXXXXXX ** command to send a response to the client requesting to set cookies; After receiving the response, the client sets a Cookie with **JSESSIONID=XXXXXXX ** on the local client. The Cookie expires at the end of the browser session.
Next, when the client sends a request to the same website each time, the request header will carry the Cookie information (including the sessionId). Then, the server obtains the value named JSESSIONID by reading the Cookie information in the request header and obtains the sessionId of the request.
The disadvantage of the Session
The Session mechanism has A disadvantage. For example, server A stores sessions. After load balancing is performed, if the traffic volume of server A surges within A period of time, it will be forwarded to SERVER B for access, but server B does not store Session of server A, which will result in Session invalidity.
What is the Cookies
Cookie in HTTP protocol includes Web Cookie and browser Cookie, which is a small piece of data sent by the server to the Web browser. Cookies sent by the server to the browser are stored by the browser and sent to the server with the next request. Typically, it is used to determine whether two requests are coming from the same browser, for example when the user remains logged in.
HTTP Cookie mechanism is a supplement and improvement of HTTP protocol stateless
Cookies are used for three purposes
- Session management
Login, shopping cart, game score, or anything else the server should remember
- personalized
User preferences, themes, or other Settings
- tracking
Record and analyze user behavior
Cookies were once used for general client storage. While these are legal because they are the only way to store data on the client, modern storage apis are recommended today. Cookies are sent with each request, so they can degrade performance (especially for mobile data connections).
Create a Cookie
When receiving an HTTP request from a client, the server can send a set-cookie header with the response, which is usually stored by the browser, and then send the Cookie with the HTTP header to the server.
Set-cookie and Cookie headers
Set-cookie THE HTTP response header sends a Cookie from the server to the user agent. Here is an example of sending cookies
This header tells the client to store the Cookie
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, Session Cookies and Persistent Cookies, which are treated as Session Cookies if they do not contain an expiration date. Session cookies are stored in memory, never written to disk, and are permanently lost thereafter when the browser is closed. If a Cookie contains an expiration date, it is considered a persistent Cookie. On the expiration date specified, the Cookie is deleted from disk.
There are also Secure and HttpOnly tokens for cookies, which are described in turn
Session Cookies
The example above creates a session Cookie, which has a feature that the Cookie is deleted when the client closes because it does not specify Expires or max-age directives.
However, Web browsers may use session restore, which leaves most session cookies in a permanent state as if the browser had never been closed.
Permanent Cookies
Permanent cookies do not expire when the client closes, but expire after 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 codeCopy the code
Secure and HttpOnly flags for cookies
Secure cookies are sent to the server in encrypted mode through HTTPS. Even if it is secure, sensitive information should not be stored in cookies because they are inherently insecure and this flag provides no real protection.
The role of HttpOnly
- The lack of HttpOnly attribute in session cookies causes attackers to obtain user Cookie information through programs (JS scripts, applets, etc.), resulting in user Cookie information disclosure and increasing the threat of cross-site scripting attacks.
- HttpOnly is a Microsoft extension to cookies that specifies whether cookies are accessible through client 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 stolen cookies to masquerade as users or obtain sensitive information for cross-site scripting attacks, etc.
Cookie 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, the current host (excluding the subdomain name) is used by default. If Domain is specified, subdomain names are generally included.
For example, if you set Domain=mozilla.org, cookies are also included in the subdomain (e.g. Developer.mozilla.org).
For example, if Path=/docs is set, the following addresses will match:
- /docs
- /docs/Web/
- /docs/Web/HTTP
Comparison of JSON Web Tokens and Session Cookies
JSON Web Tokens, or JWT, and sessions can both provide user authentication for websites, but they are not the same thing.
Here’s a look at the differences between JWT and Session
Similarities between JWT and Session Cookies
Before exploring JWT and Session Cookies, it’s important to understand what they have in common.
They can be used to authenticate users as well as when they click to go to a different page and after they log into a website or application.
If you don’t have both, you’ll probably need to log in with each page switch. Because HTTP is a stateless protocol. This means that when you visit a web page and click on another page on the same site, the server’s memory won’t remember what you did.
So if you log in and go to another page that you have access to, you will log in again because HTTP does not record that you just logged in.
JWT and Session Cookies are mechanisms to handle switching between pages and saving user login information.
In other words, both technologies are used to save your login status and allow you to visit any password-protected site. This problem is solved by authenticating user data each time a new request is made.
So what do JWT and Session Cookies have in common? That is, they allow you to record and verify your login status between different requests.
What are 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 securely created by the server.
On each request, the server reads the SessionId from the session Cookie, and if the server’s data is the same as the read SessionId, the server sends a response to the browser allowing the user to log in.
What is Json Web Tokens
Json Web tokens are JWT for short and are often referred to as Json tokens. It is defined in RFC 7519 as a form for securely transferring information as Json objects. The information stored in JWT is digitally signed so that it can be trusted and understood. JWT can be signed using the HMAC algorithm or using the public/private key of RSA/ECDSA.
JWT is used for two main purposes
- Authorization: This is the most common use of JWT. Once the user is logged in, the JWT is included in each subsequent request, 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 means of securely transferring Information. JWT signature authentication is performed using public/private keys. Also, since signatures are calculated using head and payload, you can verify that the content has been tampered with.
The format of the JWT
Next, what is the composition and format of JWT
JWT is mainly composed of three parts, each part is segmented by., each part is respectively
- Header
- Payload
- Signature
Thus, a very simple JWT composition would look like this
Then we discuss the different parts separately.
Header
The Header is the JWT Header, which usually consists of two parts: the type of token (that is, JWT) and the signature algorithm used, such as HMAC SHA256 or RSA.
For example,
{ "alg": "HS256"."typ": "JWT"} Duplicate codeCopy the code
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 Payload, and Payload contains a declaration. Declarations are declarations about entities (usually users) and other data. There are three types of declarations: registered, public and private.
- Registered declarations: contains a set of predefined declarations that are recommended for use, mainly including
ISS Issuer ISS 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 declaration: A public declaration. You can add any information, such as user information or other necessary information required by services. Sensitive information is not recommended, because it can be decrypted on the client.
- Private Declarations: Custom declarations that are intended to share information between parties that agree to use them and are neither registration nor public declarations.
For example,
{ "sub": "1234567890"."name": "John Doe"."admin": true} Duplicate codeCopy the code
The payload Json block is then Base64Url encoded to form the second part of the JWT.
signature
The third part of the JWT is a visa information, which consists of three parts
- Header (Base64)
- Payload (base64)
- secret
For example, we need HMAC SHA256 algorithm for signature
HMACSHA256( base64UrlEncode(header) + "."+ base64UrlEncode(payload), secret) Copy codeCopy the code
The signature is used to verify that the message has not changed during this process, and for tokens signed with a private key, it also verifies the real identity of the sender of the JWT
Piece together
Now we put together the above three dot-separated parts of a Base64-URL string that can be easily passed between HTML and HTTP environments.
Here is a complete JWT example that encodes header and payload and then uses signature for signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cB Ab30RMHrHDcEfxjoYZgeFONFh7HgQ copying codeCopy the code
Jwt. IO /#debugger-i…
Difference between JWT and Session Cookies
Both JWT and Session Cookies provide secure user authentication, but they differ in the following ways
Password signature
JWT has an encrypted signature, while Session Cookies do not.
JSON is stateless
JWT is stateless because declarations are stored on the client side, not in server memory.
Authentication can be done locally, rather than where 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 a site or application’s database and consume significant resources in the process.
scalability
Session Cookies are stored in server memory, which means that if the site or application is very large, it can consume a lot of resources. Because JWT is stateless, they can save server resources in many cases. JWT is therefore more scalable than Session Cookies.
JWT supports cross-domain authentication
Session Cookies are valid only for the domain of a single node or its subdomains. If they try to access through a third node, they are blocked. This is a problem if you want your site to have secure connections to other sites.
This problem can be solved by using JWT, which enables user authentication across multiple nodes, also known as cross-domain authentication.
Selection of JWT and Session Cookies
We have discussed the differences between JWT and Cookies above, and I believe you will also have a better understanding of the selection, in general
Session Cookies are usually fine for small and medium-sized web sites that just need to log in to the user and access some information stored in the site’s database.
If you have an enterprise site, an application, or a nearby site, and need to handle a lot of requests, especially from third parties or a lot of third parties (including apis in different domains), then JWT is obviously more suitable.
Afterword.
I asked this question in the interview two days ago, so I wrote an article to summarize it. I also asked an interview question: How to disable Cookies and use Session? Baidu online, found that this is the PHP interview……
But I chose to know how to disable Cookies after using Session
- If Cookies are disabled, the server still sends the sessionId to the browser as a cookie, but the browser no longer saves the cookie (the sessionId).
- If you want to continue using sessions, you need to use URL rewriting to do so, see www.cnblogs.com/Renyi-Fan/p…
Related references:
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…