当前位置:网站首页>An article takes you into the world of cookies, sessions, and tokens
An article takes you into the world of cookies, sessions, and tokens
2022-07-05 09:16:00 【Software testing】
Preface
Stateless HTTP agreement
One day , You have a need , You are going to the supermarket to buy a bottle of coke . Went to the supermarket and bought coke , You tell the salesperson , Prepare leibi for me next time , I'll get it next time . The second time , You go to the supermarket to get leibi , The salesperson said he didn't remember when you said to prepare leibi . This time you are smart , The salesperson wrote you a note , It has the seal of the supermarket , Next time you bring a note , Bought a supermarket Leibi prepared for you
1.http Hypertext transfer protocol :Hyper Text Transfer Protocol
2.http This connection will not be maintained for the information required for the next connection
3. Like you go to the supermarket to buy Coke , It's over after buying , It won't record the information you tell him , It won't be recorded that you will buy leibi next time , Next time he doesn't know you've been here
4. As the name suggests, statelessness refers to , When the browser sends a request to server When ,server Respond to , But the same browser sends a request to server When , He will respond , But he doesn't know that you are the browser just now , In short , Namely server I won't remember you , So it's a stateless protocol . and DNS It's a stateful agreement .
5. Another example , Like a shopping cart , You buy things and add them to the shopping cart , If http agreement , Refresh the page , The shopping cart is empty .
One 、cookie
cookie It's a very specific thing , It refers to a kind of data that can be stored permanently in the browser . It has nothing to do with the server , It's just a data storage function implemented by browser .
cookie Generated by the server , Send it to the browser , Browser handle cookie With KV Form is stored in a text file in a directory , The next time you request the same website, you will send the cookie Send to the server . because cookie It's on the client side , So browsers add some restrictions to make sure cookie Will not be used maliciously , It doesn't take up too much disk space at the same time . So for each domain cookie There is a limit to the quantity .
How to set up
Client side Settings
document.cookie = "name=xiaoming; age=12 "
The client can set cookie The following options for : expires, domain, path, secure( Only in https Agreement page , Client side Settings secure type cookie To take effect ), But can't set httpOnly Options
Set up cookie => cookie Automatically added to request header in => The server receives cookie
Server settings
Whether you are requesting a resource file ( Such as html/js/css/ picture ), Or send a ajax request , The server will return response. and response header One of them is called set-cookie, The server is specially used to set cookie Of ;
One set-cookie You can only set one cookie, When you want to set multiple , You need to add as many set-cookie
The server can set cookie All the options for : expires, domain, path, secure, HttpOnly
Cookie,SessionStorage,LocalStorage
HTML5 It provides two ways of local storage sessionStorage and localStorage;
Two 、Session
Cookie It's stored on the client side ,Session It's stored on the service side , The client only stores SessionId
We know what is Cookie, Now that the browser has passed Cookie The need for statefulness is realized , So why is there another Session Well ? Here let's imagine , If you put some information in your account Cookie In the words of , Once the information is intercepted , Then all our account information will be lost . So there it is Session, Keep important information in a session Session in , Browsers only record SessionId One SessionId Corresponding to a session request .
[email protected]("/testSession")
[email protected]
3public String testSession(HttpSession session){
4 session.setAttribute("testSession","this is my session");
5 return "testSession";
6}
7
8
[email protected]("/testGetSession")
[email protected]
11public String testGetSession(HttpSession session){
12 Object testSession = session.getAttribute("testSession");
13 return String.valueOf(testSession);
14}
Here we write a new method to test Session How did it come about , Let's add... To the request parameter HttpSession session, And then type... In the browser http://localhost:8005/testSession You can see in the return header of the server when you access it Cookie There's a SessionId. Then the browser remembers this SessionId You can take this with you on your next visit Id, And then you can follow that Id Find the information stored in the server .
At this point we visit the path http://localhost:8005/testGetSession, Found on top of us in Session Information in . that Session When does it expire ?
client : and Cookie The expiration date is the same , If not , The default is to close the browser , That is, when you open the browser again, the first request header does not contain SessionId 了 .
Server side : The expiration of the server is true , That is, on the server side Session How long has the stored data structure been unavailable , The default is 30 minute .
Now that we know Session It is managed on the server side , So maybe you see that there are a few questions ,Session Where was it created ?Session Is stored in what data structure ? Let's take a look at Session How is it managed .
Session The management of is managed in the container , What is a container ?Tomcat、Jetty And so on are all containers . Next let's take the most commonly used Tomcat Take... For example Tomcat How to manage Session Of . stay ManageBase Of createSession It's used to create Session Of .
[email protected]
2public Session createSession(String sessionId) {
3 // First judgement Session Is the quantity at its maximum , Maximum Session Number can be set by parameter
4 if ((maxActiveSessions >= 0) &&
5 (getActiveSessions() >= maxActiveSessions)) {
6 rejectedSessions++;
7 throw new TooManyActiveSessionsException(
8 sm.getString("managerBase.createSession.ise"),
9 maxActiveSessions);
10 }
11
12 // Reuse or create a new Session object , Please note that Tomcat The middle is StandardSession
13 // It is HttpSession Implementation class of , and HttpSession yes Servlet Interfaces defined in the specification
14 Session session = createEmptySession();
15
16
17 // Initialize new Session Value
18 session.setNew(true);
19 session.setValid(true);
20 session.setCreationTime(System.currentTimeMillis());
21 // Set up Session The expiration time is 30 minute
22 session.setMaxInactiveInterval(getContext().getSessionTimeout() * 60);
23 String id = sessionId;
24 if (id == null) {
25 id = generateSessionId();
26 }
27 session.setId(id);// Here will be Session Add to ConcurrentHashMap in
28 sessionCounter++;
29
30 // Add creation time to LinkedList in , And remove the first time added
31 // It's mainly convenient to clean up overdue Session
32 SessionTiming timing = new SessionTiming(session.getCreationTime(), 0);
33 synchronized (sessionCreationTiming) {
34 sessionCreationTiming.add(timing);
35 sessionCreationTiming.poll();
36 }
37 return session
38}
Here we understand Session How to create , When it's created Session Will be saved to a ConcurrentHashMap in . You can see StandardSession class .
1protected Map<String, Session> sessions = new ConcurrentHashMap<>();
Everyone should be right about Session Have a simple understanding of .
Session Is stored in the Tomcat In the container , So if there are multiple backend machines , So multiple machines can't share Session Of , You can use Spring Distributed Session Solutions for , Yes, it will Session On the Redis in .
3、 ... and 、Token
1、 What? Token
Token It is issued by the server when logging in for the first time , As a token for the client to make a request , An authentication mechanism used for authentication when interacting , 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 .
2、Token The role of
Token Completely managed by the application , So it can avoid the same origin strategy
Token You can avoid CSRF( Cross site request access ) attack
Token It can be stateless , Can be shared across multiple servers
Use Token Reduce the pressure on the server , Reduce frequent database queries .
3、Token The process of identity authentication
The user sends the request through the user name and password
Program to verify
The program returns a signed token To the client
The client stores token, And used to send requests every time
Verify on the server side token And return the data
4、Token Storage location
Stored in localStorage in
// Storage token To ls const { token } = res.data; window.localStorage.setItem(‘jwtToken’, token);
advantage : Unlimited storage , Will always be stored in the browser .
shortcoming : because LocalStorage Can be javascript visit , So it is vulnerable to XSS attack . So you can replicate the request header in a unified place , Make every request in header Take this with you token, When token When it fails , The back end will return 401, At this time, you can operate in the front-end code to return to the login page , eliminate localstorage Medium token.( Apply to ajax Request or api request , It can be conveniently deposited into localstorage) in addition , Applications are required to ensure that Token Only in HTTPS Down transmission .
Stored in cookie in
advantage : Can prevent csrf attack , because csrf Can only be carried in the request cookie, And here must be from cookie Take out the corresponding value in and put it in authorization In the head . actually cookie Cannot cross station ( The same-origin policy ) Was taken out , So you can avoid csrf attack .( Apply to ajax Request or api request , It can be set up conveniently auth head )
5、Token Processing expiration time
In my vue In the project , I will Token Stored in localStorage in , Has it been handled Token Be overdue , Here's how I do it :
created() {
if (localStorage.jwtToken) {
const decoded = jwt_decode(localStorage.jwtToken);
// Get the current time
const currentTime = Date.now() / 1000;
// testing token Is it overdue
if (decoded.exp < currentTime) {
// Go to the login page
this.$router.push('/login');
// Other treatments
...
} else{
// No expired processing ;
}
}
Four 、 summary
cookie,session,Token There is no absolute distinction between good and bad , As long as we still need to combine the actual business scenarios and needs to decide which way to manage the reply , Of course, you can also use all three .
The house needs to be built layer by layer , Knowledge needs to be learned at one point one . We should lay a good foundation in the process of learning , More hands-on practice , Don't talk much , The last dry goods here ! I stayed up late to sort out the stages ( function 、 Interface 、 automation 、 performance 、 Test open ) Skills learning materials + Practical explanation , Very suitable for studying in private , It's much more efficient than self-study , Share with you .
Get off w/x/g/z/h: Software testing tips dao
Typing is not easy , If this article is helpful to you , Click a like, collect a hide and pay attention , Give the author an encouragement . It's also convenient for you to find it quickly next time .
边栏推荐
- Codeworks round 639 (Div. 2) cute new problem solution
- Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
- Progressive JPEG pictures and related
- Introduction Guide to stereo vision (4): DLT direct linear transformation of camera calibration [recommended collection]
- np. allclose
- fs. Path module
- [code practice] [stereo matching series] Classic ad census: (6) multi step parallax optimization
- nodejs_ 01_ fs. readFile
- 2310. The number of bits is the sum of integers of K
- Illustrated network: what is gateway load balancing protocol GLBP?
猜你喜欢
L'information et l'entropie, tout ce que vous voulez savoir est ici.
Summary and Reflection on issues related to seq2seq, attention and transformer in hands-on deep learning
nodejs_ 01_ fs. readFile
嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!
Editor use of VI and VIM
Applet (use of NPM package)
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
Creation and reference of applet
顶会论文看图对比学习(GNN+CL)研究趋势
Blogger article navigation (classified, real-time update, permanent top)
随机推荐
AUTOSAR from getting started to mastering 100 lectures (103) -dbc file format and creation details
【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
L'information et l'entropie, tout ce que vous voulez savoir est ici.
. Net service governance flow limiting middleware -fireflysoft RateLimit
notepad++
Introduction Guide to stereo vision (6): level constraints and polar correction of fusiello method
深入浅出PyTorch中的nn.CrossEntropyLoss
Golang foundation -- map, array and slice store different types of data
Global configuration tabbar
Ecmascript6 introduction and environment construction
OpenGL - Lighting
Characteristic Engineering
顶会论文看图对比学习(GNN+CL)研究趋势
【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous
我的一生.
22-07-04 西安 尚好房-项目经验总结(01)
My life
Blue Bridge Cup provincial match simulation question 9 (MST)
Return of missing persons
生成对抗网络