当前位置:网站首页>Do you know cookies, sessions, tokens?

Do you know cookies, sessions, tokens?

2022-07-06 03:39:00 Two black

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 , Don't record. You need to buy rapit 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 .

 1@RequestMapping("/testSession")
 2@ResponseBody
 3public String testSession(HttpSession session){
    
 4    session.setAttribute("testSession","this is my session");
 5    return "testSession";
 6}
 7
 8
 9@RequestMapping("/testGetSession")
10@ResponseBody
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 .

 Insert picture description here
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 .

1@Override
 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 .

Learning resource sharing

Finally, thank everyone who reads my article carefully , Watching the rise and attention of fans all the way , Reciprocity is always necessary , Although it's not very valuable , If you can use it, you can take it

These materials , For those who want to advance 【 automated testing 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you ! Everything should be done as soon as possible , Especially in the technology industry , We must improve our technical skills . I hope that's helpful …….

Join my communication group below for free !

原网站

版权声明
本文为[Two black]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060338287158.html