当前位置:网站首页>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 .
边栏推荐
- It's too difficult to use. Long articles plus pictures and texts will only be written in short articles in the future
- [code practice] [stereo matching series] Classic ad census: (5) scan line optimization
- Introduction Guide to stereo vision (2): key matrix (essential matrix, basic matrix, homography matrix)
- C [essential skills] use of configurationmanager class (use of file app.config)
- 高性能Spark_transformation性能
- [technical school] spatial accuracy of binocular stereo vision system: accurate quantitative analysis
- Oracle advanced (III) detailed explanation of data dictionary
- Multiple linear regression (sklearn method)
- Blue Bridge Cup provincial match simulation question 9 (MST)
- Wxss template syntax
猜你喜欢
生成对抗网络
Introduction Guide to stereo vision (6): level constraints and polar correction of fusiello method
Wxml template syntax
Introduction Guide to stereo vision (2): key matrix (essential matrix, basic matrix, homography matrix)
Rebuild my 3D world [open source] [serialization-2]
Kotlin introductory notes (VIII) collection and traversal
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
顶会论文看图对比学习(GNN+CL)研究趋势
Introduction Guide to stereo vision (1): coordinate system and camera parameters
Confusing basic concepts member variables local variables global variables
随机推荐
Applet global style configuration window
Kotlin introductory notes (I) kotlin variables and non variables
AdaBoost use
Huber Loss
Introduction Guide to stereo vision (6): level constraints and polar correction of fusiello method
It's too difficult to use. Long articles plus pictures and texts will only be written in short articles in the future
Priority queue (heap)
. Net service governance flow limiting middleware -fireflysoft RateLimit
基于STM32单片机的测温仪(带人脸检测)
Ecmascript6 introduction and environment construction
asp. Net (c)
一文详解图对比学习(GNN+CL)的一般流程和最新研究趋势
信息與熵,你想知道的都在這裏了
3D reconstruction open source code summary [keep updated]
Configuration and startup of kubedm series-02-kubelet
Use arm neon operation to improve memory copy speed
Codeforces Round #648 (Div. 2) D. Solve The Maze
C form click event did not respond
Kotlin introductory notes (VII) data class and singleton class
Summary and Reflection on issues related to seq2seq, attention and transformer in hands-on deep learning