Stateless http
We all know that http requests and responsiveness are independent of each other, and the server cannot identify whether the two http requests were sent by the same user. In other words, the server does not have the ability to record communication status. We usually use cookies and sessions to determine the identity of both parties to the session.
cookie
The cookie is sent from the server side. The server sends different identifiers to different users. This identifier represents the user's identity. The server identifies the user's identity through the identifier sent by the client, thereby querying the relevant data of the user in the server and then sending it to the user.
Install the cookie-parser middleware provided by express:
npm i -S cookie-parser
Introduce the cookie-parser plugin into the project page module we use and instantiate it as follows:
var cookieParser = require('cookie-parser'); var cp = cookieParser(secret, options);
It has two parameters, the first parameter secret, which can use it to sign cookies, which is what we often call cookie encryption. It can be a string or an array. If you are familiar with the encryption principle, you should know that this string is the ciphertext owned by the server. The second parameter options contain the following optional parameters:
- path: Specify the path affected by the cookie
- expires: Specify the time format
- maxAge: Specify when the cookie expires
- secure: Only valid in HTTPS when the secure value is true; otherwise, cookies are valid in HTTP.
- httpOnly: The browser does not allow script operations to change cookies. Set to true to avoid getting cookies by xss attacks
refer tocookie-parserIn the example in, implement a demo that remembers the access path, the code is as follows:
var path = require('path'); var express = require('express'); var cookieParser = require('cookie-parser'); var app = express(); // Use cookieParser middleware;(cookieParser()); // If the cookie in the request exists isFirst// Otherwise, set the cookie field isFirst and set the expiration time to 10 seconds('/', function(req, res) { if () { ("Welcome to visit again"); () } else { ('isFirst', 1, { maxAge: 60 * 1000}); ("Welcome to the first visit"); } }); (3030, function() { ('express start on: ' + 3030) });
cookie-parser can also encrypt cookie data, which is what we call signedCookies.
signedCookies
The implementation code is as follows:
var path = require('path'); var express = require('express'); var cookieParser = require('cookie-parser'); var app = express(); // Use cookieParser middleware;(cookieParser('my_cookie_secret')); // cookie ('/', function(req, res) { if () { ("Welcome to visit again"); () } else { ('isFirst', 1, { maxAge: 60 * 1000, signed: true}); ("Welcome to the first visit"); } });
From the above code we know that the first parameter of cooke-parser can specify the encryption key provided by the server side, and then we can use the signed configuration item in options to achieve encryption. Although this is relatively safe, the client's cookies have limitations. When the client sends a request, the amount of data in the request header will increase, resulting in slower request speed; in addition, it cannot realize data sharing.
session
express-session is a middleware in expressjs to create sessions. The server side generates a sessionn-id. The client uses cookies to save the encrypted request information of session-id, and saves the data requested by the user on the server side, but it can also encrypt the user's data and save it on the client side.
The session records the session state between the client and the server, which is used to determine the identity of the client.
Express-session supports session storage location
It can be stored in cookies, or in memory, or in third-party servers such as redis and mongodb.
The session is stored in memory by default. It is too safe to store in cookies and is too slow to query in non-redis databases. It is stored in redis (cache database) in general project development.
In the express-session middleware installation command provided by express:
npm i -S express-session
Introduce the express-session plugin into the project page module we are using and instantiate it as follows:
var session = require('express-session'); var se = session(options);
The main parameters options configuration items of session() are:
- name: Set the field name of the cookie to save the session, the default is
- store: The storage method of session is stored in memory by default. We can customize redis, etc.
- genid: When generating a new session_id, the npm package uid2 is used by default.
- rolling: Reset a cookie for each request, default to false
- resave: Save the session value even if the session has not been modified, and the default is true
- saveUninitialized: Force uninitialized session to save to the database
- Secret: calculate the hash value through the set secret string and put it in the cookie, making the generated signedCookie tamper-proof
- cookies: Set options for storing sessionid cookies
So, what can we do with it? We will introduce it one by one below.
cookie session
The use of cookie session is very simple. We use the cookie configuration item in the configuration item, and we can save the session data in the cookie. It is similar to signedCookies to save the data on the client and both encrypt the data, but the data structure obtained by the encrypted request is different.
The structure of the cook session is as follows:
Session { cookie: { path: '/', _expires: 2018-01-29T17:58:49.950Z, originalMaxAge: 60000, httpOnly: true }, isFirst: 1 }
The signedCookie structure is as follows:
{ isFirst: '1' }
The cookie session code is as follows:
var path = require('path'); var express = require('express'); var session = require('express-session'); var redisStore = require('connect-redis')(session); var app = express(); // session (session({ name: 'session-name', // Here is the name of the cookie, the default is secret: 'my_session_secret', // It is recommended to use a random string of 128 characters resave: true, saveUninitialized: false, cookie: { maxAge: 60 * 1000, httpOnly: true } })); // route ('/', function(req, res, next) { if( || ) { ("Welcome to visit again"); } else { = 1; ('isFirst', 1, { maxAge: 60 * 1000, singed: true}); ("Welcome to the first visit."); } }); (3030, function() { ('express start on: ' + 3030) });
signed-cookie vs cookie session
- signedCookies information is visible but cannot be modified, and the cookie session is not visible or modified.
- signedCookies Information is stored on the client for a long time, and the latter client is closed and the information disappears.
For Cooke session, the data size of client requests is increased. We generally use this way, and the database stores the session.
Database save session
To save sessions with a database, we generally use redis because it is a cache database and query speed is faster than non-caches.
The example code of express-session is as follows:
var path = require('path'); var express = require('express'); var session = require('express-session'); var redisStore = require('connect-redis')(session); var app = express(); // session (session({ name: 'session-name', // Here is the name of the cookie, the default is secret: 'my_session_secret', // It is recommended to use a random string of 128 characters resave: true, saveUninitialized: false, store: new redisStore({ host: '127.0.0.1', port: '6379', db: 0, pass: '', }) })); // route ('/', function(req, res) { if () { ("Welcome to visit again."); () } else { = 1; ("Welcome to the first visit."); } }); (3030, function() { ('express start on: ' + 3030) });
But sometimes we also use non-redis databases to save sessions, and at this time we need to have a deep understanding and understanding of the project structure; otherwise, it will be counterproductive after use.
In addition, we should pay attention to using the database to save session data. The session-id on the browser side will disappear with the browser closing. The next time the browser is opened to send a request, the server still cannot identify the requester's identity.
Although cookie session can solve this problem, it has security risks in itself. In fact, both cookie session and signedCookies are facing xss attacks.
In fact, using a combination of signed Cookies and sessions will reduce such risks to a certain extent.
A combination of signed Cookies (cookies) and session
In development, we often need the long-term storage characteristics of signedCookies, and the invisible and unmodified characteristics of the session.
var path = require('path'); var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var redisStore = require('connect-redis')(session); var app = express(); // Use cookieParser middleware;(cookieParser()); // session (session({ name: 'session-name', // Here is the name of the cookie, the default is secret: 'my_session_secret', // It is recommended to use a random string of 128 characters resave: true, saveUninitialized: false, // cookie: { maxAge: 60 * 1000, httpOnly: true }, store: new redisStore({ host: '127.0.0.1', port: '6379', db: 0, pass: '', }) })); ('/', function(req, res, next) { if( || ) { ("Welcome to visit again"); } else { = 1; ('isFirst', 1, { maxAge: 60 * 1000, singed: true}); ("Welcome to the first visit."); } }); (3030, function() { ('express start on: ' + 3030) });
In this way, we save the information in the session in redis in a copy of the client cookie marked by session_id. In this way, we don’t have to worry about the fact that the session_id field in the cookie will disappear if the browser is closed, because there is also its backup cookie in the browser. If there is no backup cookie information, the user’s identity will not be determined the next time the client sends a request to browse again.
Reference source code
Nodejs Get started quickly
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.