How does Cookie session authentication work?

In Web applications, Cookie-Session is a standard authentication method. Cookies, also known as "sweet cookies". The type is "small text file", which refers to the data stored on the client side by some websites in order to identify the user. The main function of Session is to record the user's status through the server.

In a typical online shopping scenario, a user browses through several pages and adds some items to the cart. However, the system does not know which user performed the operation, because the HTTP protocol is stateless, so the server needs to create corresponding Session s for different users to identify and track the user. There are many ways to save Session on the server side, such as saving to memory, database or file.

Let's take a look at the authentication process of Cookie-Session:

This is a typical conversation between an HTTP client (browser) and an HTTP server running on the same computer (localhost), including the following steps.

  1. After the user visits the login page, enter the corresponding user name and password to log in.
  2. Initiate a login request on the client side. Generally, in a browser environment, a login request can be initiated through AJAX or Form.
  3. When the server passes the authentication, a Session will be created for the successfully authenticated user and the Session information will be stored. Afterwards, the server will set the SessionId through the HTTP response header, that is, the response header information Set-Cookie contained in the HTTP response header. If the authentication fails, the user is prompted to perform related operations.
  4. After the authentication is successful, the user visits the page to obtain user information. At this time, the client will carry the cookie information in the HTTP request header.
  5. The server receives the request initiated by the client, obtains the SessionId stored in the cookie to verify the user's identity, and returns the corresponding information after the verification is passed.

Below I will use Koa to introduce the authentication process of Cookie-Session. First, let's define the route of the home page:

// router.js
 router. get ( "/" , async (     ctx ) => {
 if (ctx.session.user ) { const { userName } = ctx.session.user ; ctx.body = ` < h1 > Cookie         /Session Authentication</h1>       Hello, ${userName}         <div>           <a href="./getUserInfo">User Info</a>           <a href="./logout">log out</a>         </div>         ` ;   } else {     ctx.
   









"Log in");
}
});
copy

In the above code, we will first determine whether the current user has logged into the web application. If logged in, the greeting message corresponding to the current user is displayed. If not logged in, it will jump to the login page, so we need to register the route of the login page:

// router.js
 router. get ( "/login" , ( ctx     ) => {
 if (ctx.session.user ) { ctx.redirect ( " /" );   } else { ctx.body     = ` <form method = "     post" action="/ login">       <p><label>username</label><input type="text" name="username" /></p>       <p><label>password</label><input type="password" name="password" /></p>       <button type="
copy

When a user who is not logged in visits in a browser When http://localhost:3000/login address, the following user login form will be displayed:

When the user enters the user name and password and clicks the login button, the browser will initiate a POST request and call /loginAPI. The corresponding /login route processing logic is as follows:

// router.js
 router. post ( "/login" , async (ctx) => {
 try {
   const loginData = ctx.request . body ; const
  { username, password } = loginData;
   if (username === "bytefer" && password === "123 " ) {
     ctx. session . user = { userName : "bytefer" , userId : "007" };
     ctx. response . redirect ( "/"
  }otherwise{
     ctx. body = {Code: 0, Message: "Login failed!" };
  }
} catch (err) {
   throw  new  Error ( "login error" );
}
});
copy

In the above code, we use ctx.request.body to obtain the user name and password entered by the user, and then determine whether the input user name and password match exactly. Of course, in a real web project, it is usually judged that the input information is consistent with the information in the user table of the database. In addition, to ensure the security of the system, the user's password will be encrypted or hashed. If the entered user information matches exactly, we set the currently logged in user information to the ctx.session.user property and redirect to the home page. And if the user information does not match, the corresponding error message will be displayed on the page.

Let's take a look at the HTTP response message returned by the server after successful login:

As can be seen from the above figure, after the login is successful, the HTTP response message returned by the server will contain the Set-Cookie response header. After that, we open the Application Tab page of the Chrome developer tool, and we can see the Cookie information that has been set:

For most Web applications, a user information page is generally provided, allowing users to view information about users who have successfully logged in currently. Here we also register a /getUserInfo route to display logged-in user information:

// router.js
 router. get ( "/getUserInfo" , async (     ctx ) => {
 if ( ctx.session.user ) { const { userName, userId } = ctx.session.user ; ctx.body = ` < div         > UserName           : ${userName} , UserId: ${userId}         </div>       ` ;   } else {     ctx.body = { code : 0 , message :
   






"You are not logged in. " };
}
});
copy

After the user logs in successfully, when accessing other routes in the web application, a corresponding HTTP request will be initiated, and the request header will automatically carry the Cookie information of the current user, as shown in the following figure:

In addition to the above functions, we also need to register a route to handle the user logout operation:

// router.js
 router. get ( "/logout" , async (   ctx ) => {
 ctx.session = null ; ctx.body = ` < h1   >successfully logged out</h1>   <a href="./login">Log in</a>   ` ; });
copy

Similarly, let's take a look at the HTTP response message returned by the server after the logout is successful:

Routing contained in a Web application has been described. In order for the application to run normally, we also need to create a Koa application and configure middleware such as koa-session and koa-bodyparser. The specific code is as follows:

// app.js
const  Koa = require ( "koa" );
const app = new  Koa ();
const session = require ( "koa-session" );
const bodyParser = require ( "koa-bodyparser" );

constant port = 3000 ;
const router = require ( "./router.js" );

const  CONFIG = {
 key : "sid" ,
 maxAge : 86400000 ,
 httpOnly: true ,
 signed : true ,
 rolling : false ,
 renew : false ,
 sameSite : null ,
};
application. key= [ "bytefer" ];
application. use ( async  function ( ctx, next     ) { try
{ await
   next ( );
} catch (err) {
   ctx.status = err.status || 500 ; ctx.type
= "html" ;
   CTX. body = "<p>system error</p>" ;
   CTX. application. issue("error", error, ctx);
}
});
application. use(session(configuration, application));
application. use( bodyParser ());
application. Use (router.routing()). using (router. allowedMethods());

application. on ( "error" , ( err, ctx ) => {
 console. log(err);
});

application. listen (port, function ( ) {
 console . log ( `The server runs on http://localhost: ${port} ` );
});
copy

The authentication process of Cookie-Session has been introduced, and finally some problems in this authentication method are summarized.

cookie flaws

  • Cookies are added to each HTTP request, which virtually increases traffic.
  • Poor security, attackers can exploit local cookie s for spoofing and CSRF attacks.
  • Cookie size is limited to around 4KB, which is insufficient for complex storage requirements.

session defect

  • The session is saved on the server side. If there are a large number of users in a short period of time, the performance of the server will be affected.
  • Scalability is not good. When there are multiple servers, how to share Session becomes a problem. That is to say, when the user visits server A for the first time and the second request is forwarded to server B, server B has no way of knowing its status.

So how to solve the above problems? One of the solutions is to use token based authentication. In the next article, I will introduce the JWT authentication method. Remember to follow me if you are interested.

If you need to learn the front end more comprehensively, you can also come to participate in our 30-day learning plan, which does not involve any fees! This is a set of free 30-day challenge program course system, including html+css+cloud deployment course system, you can learn through the DingTalk group, you can ask questions in the group, and each class also has homework , there are phased project exercises and comprehensive project actual combat, the purpose is to help everyone consolidate the front-end foundation and easily get started in the front-end industry

In order to help some students avoid detours and truly meet the R&D requirements of the front-end projects of the first-line Internet companies, for the first time, the strength of fans, created the "30-day challenge learning plan", the content is as follows:

HTML/HTML5, CSS/CSS3, JavaScript, real enterprise project development, cloud server deployment online, from entry to proficiency

  • PC terminal project development (1)
  • Mobile WebApp Development (2)
  • Multi-terminal responsive development (1)

A total of 4 complete project developments! Line by line of code leads practice development, we do what actual enterprise development does. Enter the working state from the beginning of the study, so as not to waste time.

Synchronously use Git to manage the version of the project code from the beginning of learning, and record study notes in Markdown, including the development standards and design specifications, naming specifications, project code specifications, and SEO optimization specifications of real big factory projects

From blue lake UI design draft to PC terminal, mobile terminal, multi-terminal responsive development project development

  • Real machine debugging, cloud service deployment online;
  • Nginx deployment in Linux environment, Nginx performance optimization;
  • Gzip compression, HTTPS encryption protocol, domain name server filing, analysis;
  • The ultimate solution for enterprise project domain name redirection, multi-site, multi-system deployment;
  • Use Git online project deployment;

These contents are covered in every detail in the "30-Day Challenge Learning Plan", including videos + graphic tutorials + project materials, etc. Only for the fans of strength, truly master the necessary skills for enterprise project development at one time, without detours!

[Not involved] any fees and interests in the process, if you are the one.

If you haven't added the assistant teacher's WeChat, you can add the WeChat below, explaining that you want to participate in the 30-day challenge learning plan, from the official account! The teacher will invite you to study and distribute relevant materials to you.

30-day challenge learning plan Web front-end from entry to actual combat | arry teacher's blog-Aiprogramming

Tags: Cyber Security http

Posted by dirkdetken on Tue, 17 Jan 2023 03:41:13 +0300