当前位置:网站首页>cookie、session、tooken
cookie、session、tooken
2022-07-02 04:04:00 【Yile】
One 、cookie The birth of
The first thing you need to know is Http Stateless connection of the Protocol , That is, this request has nothing to do with the last request , Strangers , Not related .
Server side , I don't know the relationship between the last request and this request , It is also impossible to know which client requests itself .
Now , Suppose a customer requests a login interface , And then log in , The customer needs to request the homepage , because http Stateless connection , I don't remember I requested to log in , And login succeeded , You will not see the user information of successful login on the home page .
【 The user information of the login interface cannot be shared with other pages 】
1、cookie technology — Client technology
In order to solve http Stateless connections , The problem of not being able to share data , Then data like user information , Obviously, it is the global information that several pages need to use , Every request goes to the database , It will increase the number of database accesses , At the same time, it will reduce the access speed ; So ,cookie The birth of .
cookie Put some shared information ( User information ) Stored in the browser of the client , It's global under a domain name .
2、cookie Deficiency
① cookie The amount of information stored is limited , Only a small amount of information can be stored
② cookie The stored information is in the browser of the client , For users, it is Transparent visible , Because it's on your browser , So users can modify it at will , Lead to unsafe
- Suppose if it is true cookie It stores all the information of users , Then things like user passwords can be seen transparently in browsers , It's too dangerous .
Store a small amount of shared information ( Not involving safety issues ) Information is stored in the client browser , Then other information ( Including information related to user safety ) Store to the server , This will share information ( User information ) The technology stored on the server side is session technology .
Two 、session The birth of
1、session technology — Server technology
session In fact, it is also special cookie, Only the location of information storage is on the server .Session Object stores the properties and configuration information required for a specific user session . such , When the user is in the Web When you jump between pages , Stored in Session The variables in the object will not be lost , But it's going on throughout the user session .
Session object , Guarantee All the requested operations of a user should belong to the same session , All requests from another user should belong to another session .
2、session principle
It is a set of data stored on the server . Some websites use session Mechanism to verify the identity of users .Session Object is mainly used to store the data of user session .
SessionID It needs to be stored on the browser side , Usually stored in cookie in .
When the browser sends an interface request, it needs to bring this sessionID, The server side can be based on this SessionID, Find out who the currently requested user is .
Session Generally, an expiration time is configured ,Session After expiration , The user needs to log in again .
3、session Deficiency
With more and more users of the website ,Session The space required will be larger and larger **, At the same time, single machine deployment ** Web Performance bottlenecks will appear in applications .[ stand-alone session]
At this time, we need to optimize or adjust the architecture , For example, expansion. Web Application nodes , Implement before the application server node Load balancing .[ Distributed session]
Load balancing leads to session There are problems in the management of , It's hard to guarantee All the requested operations of a user should belong to the same session , The same user will request the application A, In the application A User information recorded on the server [ The user's session Session object ], Then the user requests the application B, Now , Used to save user information to A Service , Unable to share data problem .
The problem of distributed sessions :
Solution 1: In load balancing ,nginx According to **"hash_ip" The algorithm will be the same IP Is fixed to a server **, This comes from the same ip Of session Requests always go to the same server .
Solution 2: Yes session Divestiture , hold session Data is completely stripped from the business server , Stored separately in other external devices (redis The server – Distributed cache middleware ). And external equipment redis You can also use master-slave or master-slave , Even cluster mode to achieve high availability .、
4、cookie and session The difference and choice of : Usually when combined in the project
① cookie Data is stored on the client ,session Data on the server .
② cookie unsafe ,session To compare safety
③ session Save on the server , When visits increase , It will take up the performance of your server , Consider reducing server performance , Should be used COOKIE.
session Authentication requires the server to do a lot of work to ensure session Consistency of information and session The storage , So modern web The application in the authentication solution is more inclined to the client direction ,cookie Authentication is based on the client mode , however cookie The disadvantages are obvious . Save the authentication information on the client , The key point is the verification of security ,session It's a way .
If it's just For the application scenario of user login ,session Solutions are not the only solution — be based on Token Certification of
3、 ... and 、token The birth of
At present, there are two kinds of authentication methods that can be seen on the market —— be based on Session Based on Token Of .
be based on Session Certification of , It refers to storing a Session Id. At the time of certification , The request to carry Session Id, And from Session Find the corresponding Session.
be based on Token Certification of , It refers to encoding all authentication related information into a Token(token You can think of it as a long string ), And signed by the server , To ensure that it is not tampered with .Token Itself is Plaintext Of . There is Token The information in can include, for example user id、 Permission list 、 User nicknames . So just hold the server token and token The signature of the , You can directly verify that the user's identity is legal . In reality , be based on Token The main criteria for the certification of is Json Web Token (JWT)
1、token The introduction of — Authentication of user identity
Token It is in the client side that frequently requests data from the server , The server frequently goes to the database to query the user name and password and compares them , Judge whether the user name and password are correct or not , And give corresponding prompt , In this context ,Token It came into being .
Token, Directly equivalent to an ID card , to Token Can determine your identity .
2、Token The definition of :
Token Is a string generated by the server , As a token for the client to request , After the first login , The server generates a Token This is what we call it Token Return to the client , In the future, the client only needs to bring this Token Just come and ask for data , No need to bring user name and password again .
The simplest token form :uid( Unique identity of user )、time( Timestamp of current time )、sign( Signature , from token The first few + Salt is compressed into a certain length of hexadecimal string by hash algorithm , Can prevent malicious third-party splicing token Request server ).
● When the user for the first time After successfully logging in with the account and password , The server Generate a Token And Token Failure time And return this to the client , If successful login , In the future, the client only needs to be within the effective time **
Take this with you Token Just come and ask for data , No need to bring user name and password again**.
3、 Use Token Purpose :
Token The goal is to reduce the pressure on the server , Reduce frequent database queries , Make the server more robust .
4、token verification
Every time the server verifies the client request, it carries Token, If the server signs and generates token Store in database , Then the later query verification will be time-consuming . If not stored in a database , Where should it be stored ?
— Store in memory ( Use redis cache )
Four 、jwt~ be based on Token The main standards for certification Json Web Token
Because most of the current projects are separated from each other ,api There are so many cross domain requirements ,api For authentication jwt( Use jwt To verify the user's identity ), because jwt Support cross domain use , And because of the signature , therefore JWT Can be tampered with .
1、 Cross domain session and cookie Failure problem
Because of the cross domain, the request will not be sent with cookie, and session Is based on cookie Of , therefore cookie It doesn't work session It's going to fail , So how to solve it .
2、 solve session and cookie Failure problem
Use token To simulate the session, take token Put it on the request , The front-end brings... Every request token, The back end provides an interface to the front end to obtain token.
token It's compliance JWT canonical .
3、jwt Two usage scenarios on the official website
- Authorization( to grant authorization ): This is a jwt The most widely used scenario .jwt Store data encrypted , Distribute to the front end , The front end places it in a specific header Field ( Also on params and body in ), After the server receives the request , analysis jwt Judge the user's identity , Restrict user requests .
- Information Exchange( Data exchange ): jwt Information can be encrypted by public and private keys , After communication between both parties , Get data from each other .
4、jwt There are three parts :A.B.C
A:Header,{“type”:“JWT”,“alg”:“HS256”} Fix
B:playload, Store information , Such as user id, Expiration time, etc , Can be decrypted , Can't store sensitive information
C: visa ,A and B Add the secret key Encrypted , As long as the secret key is not lost , It can be considered safe .
jwt verification , The main thing is verification C part Is it legal .
5、 ... and 、 Interview and chat cookie、session、token
These three are things with different dimensions , There's no comparison .
Cookie
It is a small piece of text data stored in the browser ; The data size does not exceed 4kb.Cookie The content of , Will follow http The request is sent to the server together , That is, when sending network requests ,cookie It will be sent to the server together in the request header .
Session
It is a set of data stored on the server . Some websites use session Mechanism to verify the identity of users .Session Object is mainly used to store the data of user session .
SessionID It needs to be stored on the browser side , Usually stored in cookie in .
When the browser sends an interface request, it needs to bring this sessionID, The server side can be based on this SessionID, Find out who the currently requested user is .
Session Generally, an expiration time is configured ,Session After expiration , The user needs to log in again .
Token
It's used in many places , It's a general term . Usually used to represent a short string .**Token Can be stored in cookie in , It can also be stored in the memory of the server , It can also be stored elsewhere .**Token and session、cookie Something that is not a dimension .
At present, there is a user authentication mechanism , The full name is json web token(jwt).
Reference article :《Token ,Cookie and Session The difference between 》https://jqiange.github.io/Token-%EF%BC%8CCookie%E5%92%8CSession%E7%9A%84%E5%8C%BA%E5%88%AB/
If this article is helpful to you, remember to give me a compliment , thank !
边栏推荐
- Opencv learning example code 3.2.4 LUT
- Use of go package
- 【无线图传】基于FPGA的简易无线图像传输系统verilog开发,matlab辅助验证
- Installation and use of blue lake
- Monkey测试
- Monkey test
- The 11th Blue Bridge Cup single chip microcomputer provincial competition
- Finally got byte offer. The 25-year-old inexperienced perception of software testing is written to you who are still confused
- Li Kou interview question 02.08 Loop detection
- WPViewPDF Delphi 和 .NET 的 PDF 查看组件
猜你喜欢
![[Li Kou brush questions] 15 Sum of three numbers (double pointer); 17. Letter combination of phone number (recursive backtracking)](/img/5e/81e613370c808c63665c14298f9a39.png)
[Li Kou brush questions] 15 Sum of three numbers (double pointer); 17. Letter combination of phone number (recursive backtracking)

近段时间天气暴热,所以采集北上广深去年天气数据,制作可视化图看下

MySQL advanced SQL statement 2

Microsoft Research Institute's new book "Fundamentals of data science", 479 Pages pdf

手撕——排序

软件测试人的第一个实战项目:web端(视频教程+文档+用例库)

The second game of the 11th provincial single chip microcomputer competition of the Blue Bridge Cup
![[wireless image transmission] FPGA based simple wireless image transmission system Verilog development, matlab assisted verification](/img/77/4df7a1439ff1a53f94d409a19a47d6.png)
[wireless image transmission] FPGA based simple wireless image transmission system Verilog development, matlab assisted verification

Delete the code you wrote? Sentenced to 10 months!

The 9th Blue Bridge Cup single chip microcomputer provincial competition
随机推荐
【小技巧】使用matlab GUI以对话框模式读取文件
Yyds dry inventory compiler and compiler tools
Influence of air resistance on the trajectory of table tennis
okcc为什么云呼叫中心比传统呼叫中心更好?
Vite: configure IP access
How about Ping An lifetime cancer insurance?
云服务器的安全设置常识
【人员密度检测】基于形态学处理和GRNN网络的人员密度检测matlab仿真
手撕——排序
[personal notes] PHP common functions - custom functions
Homework in Chapter 3 of slam course of dark blue vision -- derivative application of T6 common functions
[untitled]
Learn more about materialapp and common attribute parsing in fluent
[Li Kou brush questions] 15 Sum of three numbers (double pointer); 17. Letter combination of phone number (recursive backtracking)
Cloud service selection of enterprises: comparative analysis of SaaS, PAAS and IAAs
The confusion I encountered when learning stm32
uni-app - 实现获取手机验证码倒计时 60 秒(手机号+验证码登录功能)
Www2022 | know your way back: self training method of graph neural network under distribution and migration
手撕——排序
SQL:常用的 SQL 命令