[Illustrated HTTP reading notes] Chapter 8: Working Principles of Session and Cookie

How Cookies Work

Insert picture description here

Cookie demo

Let’s start the server to demonstrate the effect of the Cookie:
Server:
Insert picture description here
Client: (Set Cookie for the first time)
Insert picture description here
The cookie information will be added the second time, and the user’s information will be stored here:
Insert picture description here
we are looking at the server:
Insert picture description here
we still You can use Fiddler to capture packets to see the responses and requests we constructed: Insert picture description here
Understanding Cookies again: There can be multiple cookies and they are not static. For example, we demonstrate a multiple access cookieTime, each time we get a different timestamp as a cookie .
The first visit: the
Insert picture description here
second visit:
Insert picture description here
here only the time cookie is modified, the user is still the logged-in user's information, it will not be affected.

How to use cookies to complete a login process, we have to look at how this code is implemented, not only the browser, but the server must also make the corresponding logic implementation.

V3 version http server

Main work:
1. Support returning a static html file
2. Analyzing and processing cookies (processing cookies into key-value pair structure)
3. Analyzing and processing body (processing the data in body into key-value pair structure)
4. Realizing complete Login function (simple realization of session)
Here I will talk about the main code:

private void doPost(HttpRequest request, HttpResponse response) {
    
    
        // 2. 实现 /login 的处理
        if (request.getUrl().startsWith("/login")) {
    
    
            // 读取用户提交的用户名和密码
            String userName = request.getParameter("username");
            String password = request.getParameter("password");
//            System.out.println("userName: " + userName);
//            System.out.println("password: " + password);
            // 登陆逻辑就需要验证用户名密码是否正确.
            // 此处为了简单, 咱们把用户名和密码在代码中写死了.
            // 更科学的处理方式, 应该是从数据库中读取用户名对应的密码, 校验密码是否一致.
            if ("fwh".equals(userName) && "123".equals(password)) {
    
    
                // 登陆成功
                response.setStatus(200);
                response.setMessage("OK");
                response.setHeader("Content-Type", "text/html; charset=utf-8");
                // 原来登陆成功, 是给浏览器写了一个 cookie, cookie 中保存的是用户的用户名.
                // response.setHeader("Set-Cookie", "userName=" + userName);

                // 现有的对于登陆成功的处理. 给这次登陆的用户分配了一个 session
                // (在 hash 中新增了一个键值对), key 是随机生成的. value 就是用户的身份信息
                // 身份信息保存在服务器中, 此时也就不再有泄露的问题了
                // 给浏览器返回的 Cookie 中只需要包含 sessionId 即可
                String sessionId = UUID.randomUUID().toString();
                User user = new User();
                user.userName = "fwh";
                user.age = 20;
                user.school = "邮电";
                sessions.put(sessionId, user);
                response.setHeader("Set-Cookie", "sessionId=" + sessionId);

                response.writeBody("<html>");
                response.writeBody("<div>欢迎您! " + userName + "</div>");
                response.writeBody("</html>");
            } else {
    
    
                // 登陆失败
                response.setStatus(403);
                response.setMessage("Forbidden");
                response.setHeader("Content-Type", "text/html; charset=utf-8");
                response.writeBody("<html>");
                response.writeBody("<div>登陆失败</div>");
                response.writeBody("</html>");
            }
        }
    }

How session works

Insert picture description here

response.setHeader("Set-Cookie", "userName=" + userName);

If we use this line of code to implement the login retention function with the help of cookies, it is not good to do so. The user information is in the cookie. This cookie must be sent to the server again every time the data is transmitted, which means that the cookie in the cookie Information is easy to leak, and can even be forged, bypassing the login~~ So we need session!

When the server logs in successfully, save the user information in a hash table (value), and generate a key (this key is a unique string), sessionId, and finally write the sessionId into the cookie. When the page is subsequently accessed, the content in the Cookie is the sessionId, which is an irregular string, which improves security. The server can further find the user's related information through the sessionId.

String sessionId = UUID.randomUUID().toString();

This line of code will generate a random string, and each 1 call will generate a different one.
At the beginning, there is no. The response is saved by set-Cookie:
Insert picture description here
You can get it after accessing:
Insert picture description here
usually the session is matched with oneExpiration mechanism, To record when the thread was created and when it expired. If it expires, you need to log in again. Different websites set their own expiration time.

The relationship between cookie and session

  1. They are all produced to realize the interaction between the client and the server
  2. Cookie is stored on the client, the disadvantages are easy to forge and insecure
  3. Session is stored on the server side, will consume server resources
  4. There are two ways to implement Session: Cookie and URL rewriting

Reference: Deep understanding of HTTP protocol

Session management and cookie application

The standard specification based on form authentication has not yet been concluded, and cookies are generally used to manageSession(Session).

Insert picture description here

  • Step 1: The client puts the login information such as the user ID and password into the entity part of the message, and usually sends the request to the server in the POST method. At this time, HTTPS communication is used to display the HTML form screen and send user input data.
  • Step 2: The server will issue a Session ID to identify the user. Perform identity authentication by verifying the login information sent from the client, and then bind the user's authentication status to the Session ID and record it on the server.
  • Step 3: After the client receives the Session ID sent from the server, it will save it locally as a Cookie. The next time you send a request to the server, the browser will automatically send the Cookie, so the Session ID is also sent to the server. The server can identify the user and its authentication status by verifying the received Session ID.

In addition, not only is there no standardized method for login information and authentication process based on form authentication, but also how the server should save the login information such as passwords submitted by users.

Reference: "Graphic HTTP"

Guess you like

Origin blog.csdn.net/weixin_45532227/article/details/113050574