In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the differences between Cookie/Session/Token". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the differences between Cookie/Session/Token"?
Cookie
As we all know, http is a stateless protocol, and it is impossible for browsers and servers to distinguish the context of the request by its implementation.
So cookie enters the stage, and since the protocol itself can't distinguish the link, then manually carry the context information in the request header.
For example, when traveling in the past, you may need to store your luggage when you go to the scenic spot, which is weighed down by large and small bags, and you are not happy to travel. After storing your luggage, the waiter will give you a sign indicating which grid your luggage is in, and when you leave, you will be able to successfully retrieve your luggage with this sign and the number above.
This is exactly what cookie does. Passengers are like clients, and storage is like servers. With a sign with numbers written on it, the check-in (server) can distinguish different passengers (clients).
Do you think that if the brand is stolen, the cookie will also be stolen? Indeed, this is a very often mentioned network security issue-CSRF. You can learn about the causes and countermeasures of CSRF in this article.
At the beginning of its birth, cookie seems to be used for e-commerce to store data such as users' shopping carts, but now there are two storage (local, session) and two kinds of databases (websql, IndexedDB) at the front end, so there is no problem of storing information at all, so now it is basically 100% to prove the identity of the client on the connection. For example, after logging in, the server gives you a logo, which is stored in cookie, and then when you connect, it will automatically bring cookie, and the server will distinguish who is who. In addition, cookie can also be used to track a user, which raises privacy issues, leading to the option of "disable cookie" (however, it is troublesome to disable cookie in this day and age).
Setting mode
The real-world example shows how to set up cookie in a computer. In general, for security reasons, cookie relies on the set-cookie header setting, and the JavaScript setting is not allowed.
Set-Cookie: = Set-Cookie: =; Expires= Set-Cookie: =; Max-Age= Set-Cookie: =; Domain= Set-Cookie: =; Path= Set-Cookie: =; Secure Set-Cookie: =; HttpOnly Set-Cookie: =; SameSite=Strict Set-Cookie: =; SameSite=Lax Set-Cookie: =; SameSite=None; Secure / / Multiple attributes are also possible, for example: Set-Cookie: =; Domain=; Secure; HttpOnly
Among them = such kv pairs, the content is up to you, and there are also HttpOnly, SameSite and other configurations, and only one cookie is configured for a Set-Cookie.
Expires sets the expiration time (timestamp) of the cookie, which is the client time.
Max-Age sets the retention time of cookie (in seconds). If both Expires and Max-Age exist, Max-Age takes precedence.
The domain name for which the Domain setting takes effect. The default is the current domain name and does not contain subdomain names.
Path sets the effective path, / full match
Secure sets cookie to be sent only under https to prevent man-in-the-middle attacks
HttpOnly setting prevents JavaScript from accessing cookie and prevents XSS
SameSite sets cross-domain settings without carrying cookie to prevent CSRF.
Secure and HttpOnly are highly recommended. The SameSite option needs to be discussed according to the actual situation, because SameSite may cause a series of problems because the request does not come with cookie, even if you solve the leapfrog problem with CORS. At first, you thought it was an axios configuration problem, but it doesn't matter at all.
In fact, because Chrome defaults the unset SameSite to Lax after an update, you will not automatically bring cookie if you manually set SameSite to None on the server.
Sending mode
The sending format of reference MDN,cookie is as follows (which will be mentioned below about PHPSESSID):
Cookie: Cookie: name=value Cookie: name=value; name2=value2; name3=value3 Cookie: PHPSESSID=298zf09hf012fh3; csrftoken=u32t4o3tb3gg43; _ gat=1
When sending cookie, the configuration mentioned above will not be sent to the server, because the server does not need to care about this information after it is set up, as long as the modern browser is working properly, the received cookie will be fine.
Session
From cookie to session, it is because session is the real "information". As mentioned above, cookie is a container with PHPSESSID=298zf09hf012fh3;, in it, which is a session ID.
I wonder if session and session id will make you a little dizzy?
The original existence of session is to provide information for client and server connections, so I understand session as information, and session id is the key to information, usually a unique hash code.
Next, we analyze the middleware of two node.js express and understand the implementation of the two session.
Session information can be stored on a client, such as cookie-session, or on a server, such as express-session. To use session ID is to put session in the server and use the id in cookie to find the server's information.
Client storage
For the cookie-session library, it is easier to understand, in fact, all the information is encrypted and stuffed into the cookie. The cookies library is involved. When you set up session, you actually call cookies.set, write the information to set-cookie, and then return to the browser. In other words, the essence of values and assignments is to manipulate cookie.
After receiving the set-cookie header, the browser will write the information to the cookie. The next time the request is sent, the information is brought back as is through the cookie, so the server does not need to store anything but is responsible for obtaining and processing the information in the cookie. This implementation does not require session ID.
This is a piece of code that uses cookie-session middleware to add cookie to the request:
Const express = require ('express') var cookieSession = require (' cookie-session') const app = express () app.use (cookieSession ({name: 'session', keys: [/ * secret keys * /' key',], / / Cookie Options maxAge: 24 * 60 * 60 * 1000, / / 24 hours}) app.get ('/', function (req) Res) {req.session.test = 'hey' res.json ({wow:' crazy',})}) app.listen (3001)
Before using the middleware through app.use (cookieSession ()), the request will not set cookie, and then access it after adding it (and after setting req.session, if you do not add session information, there is no need to write, and there is no content to write to cookie), you can see that the following two lines have been added to the server response header, writing session and session.sig respectively:
Set-Cookie: session=eyJ0ZXN0IjoiaGV5In0=; path=/; expires=Tue, 23 Feb 2021 01:07:05 GMT; httponly Set-Cookie: session.sig=QBoXofGvnXbVoA8dDmfD-GMMM6E; path=/; expires=Tue, 23 Feb 2021 01:07:05 GMT; httponly
Then you can see that cookie has been successfully written in the Application tag of DevTools. The value of session eyJ0ZXN0IjoiaGV5In0= is decoded by base64 (if you don't know base64, you can see here), you can get {"test": "hey"}, which is the so-called "put session information on the client", because base64 encoding is not encrypted, which is no different from plaintext transmission, so please do not put confidential information such as user passwords in the client session.
Even if modern browsers and servers make some conventions, such as the use of https, cross-domain restrictions, and the httponly and sameSite configuration of cookie mentioned above, cookie security is ensured. But come to think of it, transmission security is guaranteed. If someone takes a peek at the cookie on your computer and the password happens to exist in cookie, you can steal the password silently. On the contrary, if you only put other information or just prove that the "logged in" flag, as long as you exit once, the cookie will be invalid, which can be regarded as reducing the potential danger.
Back to the second value, session.sig, which is a 27-byte SHA1 signature to verify whether session has been tampered with, is another layer of security for cookie.
Server storage
Since it is to be stored on the server, express-session needs a container store, which can be memory, redis, mongoDB, etc., memory should be the fastest, but the restart program is gone, redis can be used as an alternative, and the scenario of using data storage session does not feel much.
The source code of express-session is not as simple and easy to understand as cookie-session, there is a bit of a winding question, how on earth is req.session inserted?
You can skip this section without paying attention to the implementation, and if you are interested, you can follow the train of thought and take a look at the source code of express-session.
We can start with the keyword .session = and find:
Store.generate rejects this, so it's easy to see that this is for initialization.
Store.prototype.createSession this is based on the req and sess parameters to set the session property in req. Yes, it is you.
So search createSession globally and lock the inflate (meaning padding) function in index.
Finally, looking for the call point of inflate is the callback function of store.get that uses sessionID as an argument, and it all makes sense--
After monitoring the cookie sent by the client, you can get the sessionID from cookie, and then use id to get the session information in store and hang it to req.session. Through this middleware, you can successfully use the session in req.
What about the assignment? This is different from the above stored in the client, the above needs to modify the client cookie information, but for the case stored on the server, you modify the session that is "actually modified", without other fancy methods, the information in memory is modified, and the next time you get the corresponding information in memory is also the modified information. (limited to memory implementation, additional writes are still required when using the database)
If there is no session id in the request, create a new session through store.generate. When you write session, the cookie can not be changed, just access the session information in memory according to the original cookie.
Var express = require ('express') var parseurl = require (' parseurl') var session = require ('express-session') var app = express () app.use (session ({secret:' keyboard cat', resave: false, saveUninitialized: true,}) app.use (function (req, res) Next) {if (! req.session.views) {req.session.views = {}} / / get the url pathname var pathname = parseurl (req). Pathname / / count the views req.session.views [pathname] = (req.session.views [pathname] | | 0) + 1 next () app.get ('/ foo', function (req, res, next) {res.json ({session: req.session) }) app.get ('/ bar', function (req, res, next) {res.send ('you viewed this page' + req.session.views ['/ bar'] + 'times')}) app.listen (3001)
Comparison of two storage methods
First of all, there is the most important philosophical issue in the computer world: the choice between time and space.
The storage on the client frees up the memory of the server storing session, but every time it brings a pile of session information processed by base64, if the amount is large, the transmission will be very slow.
Stored on the server instead, the bandwidth is saved with the server's memory.
In addition, there is also a difference in the implementation and results of logout.
The case stored on the server is simple: if req.session.isLogin = true is logged in, then req.session.isLogin = false is exited.
However, it is very difficult for the state to be stored on the client side to achieve a real "immediate logout". You can add the expiration date to the session message, or you can rely directly on the expiration date of the cookie. After the expiration, it is considered as an exit.
But if you don't want to wait until session expires, you want to log out now! What shall I do? If you think about it, you will find that there is really no way to rely solely on the session information stored on the client side.
Even if you delete the client cookie through req.session = null, it is only deleted, but if someone has copied the cookie, the cookie in his hand is valid until the expiration time in the session message.
Saying "immediate logout" is a bit of a headline party, but what I want to say is that you can't abolish a session immediately, which may cause some hidden dangers.
Token
When session is done, what is the keyword token that appears with a high frequency?
Google might as well search the word token and you can see several familiar images popping up (for older people): codec. In the past, online banking can not transfer money as long as SMS authentication, but also go through a codec, which shows a changed password. When you transfer money, you need to enter the code in the codec to transfer money. This is an example in the real world of token. Prove your identity with a string of codes or a number, isn't it the same as the baggage problem mentioned above?
In fact, the function of token is exactly the same as that of session id. It's okay to call session id session token (that's the alias written in Wikipedia).
The difference is that session id is usually stored in cookie and automatically put on; token generally requires you to actively put it in the request, such as setting the Authorization of the request header to bearer:.
However, what is mentioned above is a general situation and there is no clear stipulation at all!
Spoiler, next to talk about JWT (JSON Web Token)! He's a token! But there are session messages in it! Put it on the client side, and you can choose to put it on cookie or add it manually on Authorization! But his name is token!
Personally, I don't think you can judge whether it is token or session id by its location, nor can you judge whether it is token or session information by its content. Session, session id and token are all stream-of-consciousness things, as long as you understand what it is and how to use it, it doesn't matter how to call it.
In addition, when searching for information, I also saw some articles saying that the difference between session and token is the difference between new and old technologies, which seems to make some sense.
In the HTTP session token column of session's Wikipedia page, for example, there are more traditional technologies such as JSESSIONID (JSP), PHPSESSID (PHP), CGISESSID (CGI), ASPSESSIONID (ASP), just like SESSIONID is their pronoun; while in the study of API interfaces and OAuth3.0 login on various platforms, the word access token is used, this difference is really interesting.
Once you understand the connection between session and token, where can you see a "live" token?
Open GitHub to enter the settings, find Settings / Developer settings, and you can see the Personal access tokens option. After generating a new token, you can take it through GitHub API to prove that "you are who you are".
The keyword Access token is also used in the OAuth system, and friends who have written about logging in on Wechat should be able to feel what token is.
Token in the authority proof is really important, do not disclose, who gets the token, who is the "master". So to do a Token system, refresh or delete Token is necessary, so as to make up for the problem of token leakage as soon as possible.
After understanding the three keywords and two storage methods, let's officially start talking about the knowledge related to "user login" and the two login specifications-JWT and OAuth3.0.
Then you may see the words Authentication and Authorization frequently. They both start with Auth, but they don't mean the same thing. Simply put, the former is authentication and the latter is authorization. When writing the login system, it is necessary to verify the user's identity, set the login status, and send token to the user is authorization.
JWT
The full name is JSON Web Token (RFC 7519). Yes, JWT is a token. To make it easier to understand, I'll tell you in advance that JWT is stored in the client above, so the names mentioned above may be used frequently in this section.
structure
Although JWT is a way for clients to store session information, JWT has its own structure: Header.Payload.Signature (divided into three parts, used. Separate)
Header
{"alg": "HS256", "typ": "JWT"}
Typ indicates that the token type is JWT,alg which represents the signature algorithm, such as HMAC, SHA256, RSA, etc. Then encode it with base64.
Payload
{"sub": "1234567890", "name": "John Doe", "admin": true}
Payload is the place where the session information is placed, and finally the information is encoded by base64, and the result is similar to the session information stored by the client above.
However, JWT has some agreed attributes, called Registered claims, including:
Iss (issuer): issuer
Exp (expiration time): expiration time
Sub (subject): topic
Aud (audience): audience
Nbf (Not Before): effective time
Iat (Issued At): time of issue
Jti (JWT ID): number
Signature
The last part is the signature, which, like the session.sig mentioned above, is used to prevent tampering, but JWT combines the signature with the content.
The algorithm for generating JWT signatures is as follows:
HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret)
Use alg's algorithm in Header and self-set key secret to encode base64UrlEncode (header) + "." + base64UrlEncode (payload)
Finally, the three parts will be adopted. Together, you can vividly see the composition of JWT through jwt.io Debugger:
How to use
After authenticating the user and logging in successfully, the user will be returned to JWT. Because the JWT information is not encrypted, do not put a password in it. The details are mentioned in the cookie stored on the client.
When a user accesses a connection that requires authorization, he or she can place the token in the cookie or put Authorization: Bearer in the request header. (manual placement in the request header is not restricted by CORS and is not afraid of CSRF)
This can be used for home login or for third-party login. Single sign-on is also a common area of JWT.
JWT also has the problem that it can't invalidate itself because the information is stored on the client, which is a disadvantage of JWT.
HTTP authentication
HTTP authentication is a standardized verification method and does not use cookie and session related technologies. The request header has an authorization field in the format Authorization: Basic.
Where credentials is the user name +: + password (or token) encoded by Base64. When you see Basic authentication later, you will realize that it is good to have your user name and password on every request.
Basic authentication is probably more suitable for serverless, after all, he doesn't have running memory and can't record session, so he just takes verification with him every time.
OAuth 2.0
OAuth 2.0 (RFC 6749) is also a protocol authorized by token, which is characterized by the fact that you can use other interfaces in a limited range, or you can use other login systems to log in to your own applications, that is, third-party applications. (attention, OAuth 2.0 authorization process may be the interview Hong Kong Certificate of Education examination! )
Since it is a third-party login, there must be a third-party login server besides the application itself. There are three roles involved in OAuth 2.0: user, application provider, and login platform. The mutual invocation relationships are as follows:
+-+-+ | |-- (A)-Authorization Request-> | Resource | Owner | Authorization | | Client | | Server | | | Resource | Server |
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.