Home > Web Front-end > JS Tutorial > body text

How to use session and cookie methods in express (detailed tutorial)

亚连
Release: 2018-06-08 17:50:41
Original
1827 people have browsed it

This article mainly introduces how express uses session and cookie. Now I share it with you and give it as a reference.

Stateless http

We all know that http requests and responses are independent of each other, and the server cannot identify whether two http requests are 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 identities of both parties in the session.

cookie

Cookie is sent from the server. The server sends different identifiers to different users. This identifier represents the user's identity. The server sends it through the client. This identifier is used to identify the user, thereby querying the user's relevant data in the server and then sending it to the user.

Install the cookie-parser middleware provided by express:

npm i -S cookie-parser
Copy after login

Introduce the cookie-parser plug-in into the project page module we use, and then instantiate it, as follows:

var cookieParser = require('cookie-parser');
var cp = cookieParser(secret, options);
Copy after login

It has two parameters. The first parameter is secret, which can be used to sign cookies, which is what we often call cookie encryption. It can be a string or an array. Students who are familiar with encryption principles should know that this string is the ciphertext owned by the server. The second parameter options contains the following optional parameters:

  1. path: Specify the path affected by the cookie

  2. expires: Specify the time format

  3. maxAge: Specify when the cookie expires

  4. secure: When the secure value is true, it is only valid in HTTPS; otherwise, the cookie is valid in HTTP.

  5. httpOnly: The browser does not allow scripts to operate document.cookie to change cookies. Setting it to true can avoid being attacked by 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();

// 使用 cookieParser 中间件;
app.use(cookieParser());

// 如果请求中的 cookie 存在 isFirst
// 否则,设置 cookie 字段 isFirst, 并设置过期时间为10秒
app.get('/', function(req, res) {
  if (req.cookies.isFirst) {
    res.send("再次欢迎访问");
    console.log(req.cookies)
  } else {
    res.cookie('isFirst', 1, { maxAge: 60 * 1000});
    res.send("欢迎第一次访问");
  }
});

app.listen(3030, function() {
  console.log('express start on: ' + 3030)
});
Copy after login

From the above code we know that the first parameter of cooke-parser can specify the server-side provider Encryption key, and then we use the signed configuration item in options to implement encryption. Although this is relatively safe, the client's cookie has limitations. When the client sends a request, it will increase the amount of data in the request header, causing the request speed to slow down; in addition, it cannot achieve data sharing.

session

express-session is a middleware of expressjs used to create sessions. The server generates a session-id, and the client uses a cookie to save the encrypted request information of session-id, and saves the data requested by the user on the server. However, it can also encrypt the user's data and save it on the client. end.

session records the session status 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, in memory, or in third-party servers such as redis and mongodb.

Session is stored in memory by default. The security of storing it in cookies is too low, and the query speed of storing it in a non-redis database is too slow. In general project development, it is stored in redis (cache database).

Install the express-session middleware installation command provided by express:

var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();

// 使用 cookieParser 中间件;
app.use(cookieParser('my_cookie_secret'));

// cookie
app.get('/', function(req, res) {
  if (req.signedCookies.isFirst) {
    res.send("欢迎再一次访问");
    console.log(req.signedCookies)
  } else {
    res.cookie('isFirst', 1, { maxAge: 60 * 1000, signed: true});
    res.send("欢迎第一次访问");
  }
});
Copy after login

Introduce the express-session plug-in into the project page module we use, and then instantiate it, as follows:

npm i -S express-session
Copy after login

session() parameter options configuration items mainly include:

name: Set the cookie to save the field name of the session, the default is connect.sid

    store: The storage method of session, the default is to store in memory, we can customize redis, etc.
  1. genid: When generating a new session_id, the default is to use uid2 This npm package
  2. rolling: Reset a cookie for each request, the default is false
  3. resave: Even if the session has not been modified, Save the session value, the default is true
  4. saveUninitialized: Force the uninitialized session to be saved to the database
  5. secret: Pass the set secret string, To calculate the hash value and put it in the cookie to make the generated signedCookie tamper-proof
  6. cookie: Set the relevant options for the cookie that stores the sessionid
  7. So, what can we do with it? Below we will introduce them one by one.
  8. cookie session

Cookie session is very simple to use. We use the cookie configuration item in the configuration item to save the session data in the cookie. It is similar to signedCookies. Both save the data on the client and encrypt the data, but the data structure obtained by the encrypted request is different.

The structure of cooke session is as follows:

var session = require('express-session');
var se = session(options);
Copy after login
signedCookie structure is as follows:

Session {
 cookie:
  { path: '/',
   _expires: 2018-01-29T17:58:49.950Z,
   originalMaxAge: 60000,
   httpOnly: true },
 isFirst: 1 }
Copy after login

The code to implement cookie session is as follows:

{ isFirst: '1' }
Copy after login

signed-cookie vs cookie session

signedCookies information is visible but cannot be modified, cookie session is invisible and cannot be modified

    signedCookies information is stored on the client for a long time, The latter client is closed and the information disappears

针对Cooke session增加了客户端请求的数据规模,我们一般这样使用,数据库存储session。

数据库保存session

用数据库保存session,我们一般使用redis,因为它是缓存数据库,查询速度相较于非缓存的速度更快。

express-session 的实例代码如下:

var path = require('path');
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();

// session
app.use(session({
  name: 'session-name', // 这里是cookie的name,默认是connect.sid
  secret: 'my_session_secret', // 建议使用 128 个字符的随机字符串
  resave: true,
  saveUninitialized: false,
  store: new redisStore({
    host: '127.0.0.1',
    port: '6379',
    db: 0,
    pass: '',
  })
}));

// route
app.get('/', function(req, res) {
  if (req.session.isFirst) {
    res.send("欢迎再一次访问。");
    console.log(req.session)
  } else {
    req.session.isFirst = 1;
    res.send("欢迎第一次访问。");
  }
});

app.listen(3030, function() {
  console.log('express start on: ' + 3030)
});
Copy after login

但有时我们也使用非redis数据库保存session,这时我们就需要对项目结构有深刻的认识和理解;否则,使用后反而会适得其反。

另外,我们要注意使用数据库保存session数据,在浏览器端的session-id会随着浏览器的关闭而消失,下次打开浏览器发送请求时,服务器依然不能识别请求者的身份。

cookie session 虽然能解决这个问题,但是它本身存在着安全风险,其实cookie session 和 signedCookies都面临xss攻击。

其实,使用signedCookies和session的结合会在一定程度上降低这样的风险。

signedCookies(cookies) 和 session的结合

在开发中,我们往往需要signedCookies的长期保存特性,又需要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();

// 使用 cookieParser 中间件;
app.use(cookieParser());

// session
app.use(session({
  name: 'session-name', // 这里是cookie的name,默认是connect.sid
  secret: 'my_session_secret', // 建议使用 128 个字符的随机字符串
  resave: true,
  saveUninitialized: false,
  // cookie: { maxAge: 60 * 1000, httpOnly: true },
  store: new redisStore({
    host: '127.0.0.1',
    port: '6379',
    db: 0,
    pass: '',
  })
}));

app.get('/', function(req, res, next) {
  if(req.session.isFirst || req.cookies.isFirst) {
    res.send("欢迎再一次访问");
  } else {
    req.session.isFirst = 1;
    res.cookie('isFirst', 1, { maxAge: 60 * 1000, singed: true});
    res.send("欢迎第一次访问。");
  }
});

app.listen(3030, function() {
  console.log('express start on: ' + 3030)
});
Copy after login

这样我们将session保存在redis中的信息,保存在了session_id所标示的客户端cooke中一份,这样我们就不用担心,浏览器关闭,cookie中的session_id字段就会消失的情况,因为浏览器中还有它的备份cookie,如果没有备份的cookie信息,下次客户端再次发出请求浏览就无法确定用户的身份。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在ES6中详细解读let和闭包

在vue+iview+less+echarts中实战项目(详细教程)

详细解说vue编码风格

The above is the detailed content of How to use session and cookie methods in express (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template