Table of Contents
Getting Started Example: Cookie Settings and Parsing
Advanced example: cookie signature and parsing
Home Web Front-end JS Tutorial Comprehensive mastery of Express cookie-parser middleware

Comprehensive mastery of Express cookie-parser middleware

Feb 02, 2018 am 09:57 AM
express middleware

cookie-parser is Express's middleware, which is used to implement cookie parsing. It is one of the middleware built into the official scaffolding. It is very simple to use, but you may occasionally encounter problems during use. This is usually caused by a lack of understanding of the signature and verification mechanisms of Express + cookie-parser. This article mainly introduces to you the Express cookie-parser middleware implementation example. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Let’s look at the use of cookie-parser from the simplest example. The default configuration is used here.

  1. Cookie settings: Use Express's built-in method res.cookie().

  2. Cookie parsing: Use cookie-parser middleware.

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.use(function (req, res, next) {
 console.log(req.cookies.nick); // 第二次访问,输出chyingp
 next();
});

app.use(function (req, res, next) { 
 res.cookie('nick', 'chyingp');
 res.end('ok');
});
app.listen(3000);
Copy after login

In the current scenario, the cookie-parser middleware is roughly implemented as follows:

app.use(function (req, res, next) {
 req.cookies = cookie.parse(req.headers.cookie);
 next();
});
Copy after login

Out of For security reasons, we usually need to sign cookies.

The example is rewritten as follows, with a few points to note:

  1. When cookieParser is initialized, pass in secret as the signature key.

  2. When setting a cookie, set signed to true, indicating that the cookie to be set will be signed.

  3. When obtaining cookies, you can obtain them through req.cookies or req.signedCookies.

  4. ##
    var express = require('express');
    var cookieParser = require('cookie-parser');
    var app = express();
    // 初始化中间件,传入的第一个参数为singed secret
    app.use(cookieParser('secret'));
    app.use(function (req, res, next) {
     console.log(req.cookies.nick); // chyingp
     console.log(req.signedCookies.nick); // chyingp
     next();
    });
    app.use(function (req, res, next) { 
     // 传入第三个参数 {signed: true},表示要对cookie进行摘要计算
     res.cookie('nick', 'chyingp', {signed: true});
     res.end('ok');
    });
    app.listen(3000);
    Copy after login
The cookie value before signing is chyingp, the cookie value after signing is s%3Achyingp.uVofnk6k%2B9mHQpdPlQeOfjM8B5oa6mppny9d%2BmG9rD0, and the cookie value after decoding is s:chyingp.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9 d+mG9rD0.

Let’s analyze how cookie signature and parsing are implemented.

Analysis of cookie signature and verification implementation

Express completes the signature of cookie values, and cookie-parser implements the parsing of signed cookies. Both share the same secret key.

Cookie signature

Express’s cookie settings (including signatures) are all implemented through the res.cookie() method.

The simplified code is as follows:

res.cookie = function (name, value, options) { 
 var secret = this.req.secret;
 var signed = opts.signed;
 // 如果 options.signed 为true,则对cookie进行签名
 if (signed) {
  val = 's:' + sign(val, secret);
 }
 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));
 return this;
};
Copy after login
sign is the signature function. The pseudo code is as follows, which actually concatenates the original value of the cookie with the value after hmac.

Knock on the blackboard to highlight: the signed cookie value contains the original value.

function sign (val, secret) {
 return val + '.' + hmac(val, secret);
}
Copy after login
Where does the secret here come from? It is passed in when cookie-parser is initialized. As shown in the following pseudo code:

var cookieParser = function (secret) {
 return function (req, res, next) {
  req.secret = secret;
  // ...
  next();
 };
};
app.use(cookieParser('secret'));
Copy after login
Signed cookie parsing

After knowing the mechanism of cookie signature, it is clear how to "parse" the signed cookie. At this stage, the middleware mainly does two things:

  1. Extract the original value corresponding to the signed cookie

  2. Verify whether the signed cookie is legal

The implementation code is as follows:

// str:签名后的cookie,比如 "s:chyingp.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0"
// secret:秘钥,比如 "secret"
function signedCookie(str, secret) {

 // 检查是否 s: 开头,确保只对签过名的cookie进行解析
 if (str.substr(0, 2) !== 's:') {
  return str;
 }

 // 校验签名的值是否合法,如合法,返回true,否则,返回false
 var val = unsign(str.slice(2), secret);
 
 if (val !== false) {
  return val;
 }

 return false;
}
Copy after login
It is relatively simple to judge and extract the original value of the cookie. It’s just that the name of the unsign method is confusing.

Generally, only the signature will be legally verified, and there is no so-called counter-signature.

The code of the unsign method is as follows:

  1. First, extract the original value A1 and signature value B1 from the incoming cookie value.

  2. Secondly, use the same secret key to sign A1 to obtain A2.

  3. Finally, determine whether the signature is legal based on whether A2 and B1 are equal.

exports.unsign = function(val, secret){

 var str = val.slice(0, val.lastIndexOf('.'))
  , mac = exports.sign(str, secret);
 
 return sha1(mac) == sha1(val) ? str : false;
};
Copy after login
The role of cookie signature

is mainly for security reasons to prevent cookies from being Tampering, enhanced security.

Let’s take a small example to see how cookie signature can prevent tampering.

Expand based on the previous example. Assume that the website uses the nick cookie to distinguish who is the currently logged in user. In the previous example, in the cookie of the logged-in user, the corresponding value of nick is as follows: (after decode)

s:chyingp.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0


At this time, someone Try to modify this cookie value to achieve the purpose of forging identity. For example, change it to xiaoming:

s:xiaoming.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0


When the website receives the request, it parses the signature cookie and finds that the signature verification fails. It can be judged from this that the cookie is forged.

hmac("xiaoming", "secret") !== "uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0"


Will a signature ensure security?

Of course not .

The example in the previous section only uses the value of the nick cookie to determine which user is logged in. This is a very bad design. Although it is difficult to forge signed cookies when the secret key is unknown. But when the username is the same, the signature is also the same. In this case, it is actually very easy to forge.

In addition, the algorithms of open source components are public, so the security of the secret key becomes the key, and it is necessary to ensure that the secret key is not leaked.

There are many more, so I won’t go into them here.

Summary

This article mainly provides a relatively in-depth introduction to the signature and parsing mechanism of Express + cookie-parser.

In many similar summary articles, the cookie signature is described as encryption. This is a common mistake and readers need to pay attention to it.

The introduction to the signature part involves a little bit of simple security knowledge. Students who are unfamiliar with this part can leave a message to communicate. For the convenience of explanation, some paragraphs and wording may not be rigorous enough. If there are any errors or omissions, please point them out.

Related recommendations:

node builds its own server instance by implementing express

Node.js uses Express.Router instance Detailed explanation

Using Session in the Express framework to implement authentication at login

The above is the detailed content of Comprehensive mastery of Express cookie-parser middleware. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the principle of tomcat middleware What is the principle of tomcat middleware Dec 27, 2023 pm 04:40 PM

The principle of tomcat middleware is implemented based on Java Servlet and Java EE specifications. As a Servlet container, Tomcat is responsible for processing HTTP requests and responses and providing the running environment for Web applications. The principles of Tomcat middleware mainly involve: 1. Container model; 2. Component architecture; 3. Servlet processing mechanism; 4. Event listening and filters; 5. Configuration management; 6. Security; 7. Clustering and load balancing; 8. Connector technology; 9. Embedded mode, etc.

How to handle form validation using middleware in Laravel How to handle form validation using middleware in Laravel Nov 02, 2023 pm 03:57 PM

How to use middleware to handle form validation in Laravel, specific code examples are required Introduction: Form validation is a very common task in Laravel. In order to ensure the validity and security of the data entered by users, we usually verify the data submitted in the form. Laravel provides a convenient form validation function and also supports the use of middleware to handle form validation. This article will introduce in detail how to use middleware to handle form validation in Laravel and provide specific code examples.

How to use middleware for data acceleration in Laravel How to use middleware for data acceleration in Laravel Nov 02, 2023 am 09:40 AM

How to use middleware for data acceleration in Laravel Introduction: When developing web applications using the Laravel framework, data acceleration is the key to improving application performance. Middleware is an important feature provided by Laravel that handles requests before they reach the controller or before the response is returned. This article will focus on how to use middleware to achieve data acceleration in Laravel and provide specific code examples. 1. What is middleware? Middleware is a mechanism in the Laravel framework. It is used

How to use middleware for response transformation in Laravel How to use middleware for response transformation in Laravel Nov 03, 2023 am 09:57 AM

How to use middleware for response conversion in Laravel Middleware is one of the very powerful and practical features in the Laravel framework. It allows us to process requests and responses before the request enters the controller or before the response is sent to the client. In this article, I will demonstrate how to use middleware for response transformation in Laravel. Before starting, make sure you have Laravel installed and a new project created. Now we will follow these steps: Create a new middleware Open

How to use middleware for data recovery in Laravel How to use middleware for data recovery in Laravel Nov 02, 2023 pm 02:12 PM

Laravel is a popular PHP web application framework that provides many fast and easy ways to build efficient, secure and scalable web applications. When developing Laravel applications, we often need to consider the issue of data recovery, that is, how to recover data and ensure the normal operation of the application in the event of data loss or damage. In this article, we will introduce how to use Laravel middleware to implement data recovery functions and provide specific code examples. 1. What is Lara?

How to use middleware for scheduled task scheduling in Laravel How to use middleware for scheduled task scheduling in Laravel Nov 02, 2023 pm 02:26 PM

How to use middleware for scheduled task scheduling in Laravel Introduction: Laravel is a popular PHP open source framework that provides convenient and powerful tools to develop web applications. One of the important features is scheduled tasks, which allows developers to run specific tasks at specified intervals. In this article, we will introduce how to use middleware to implement Laravel's scheduled task scheduling, and provide specific code examples. Environment Preparation Before starting, we need to make sure

How to use middleware to set up cross-domain resource sharing (CORS) in the Slim framework How to use middleware to set up cross-domain resource sharing (CORS) in the Slim framework Jul 30, 2023 pm 08:34 PM

How to set up Cross-Origin Resource Sharing (CORS) using middleware in the Slim framework Cross-Origin Resource Sharing (CORS) is a mechanism that allows the server to set some additional information in the HTTP response header to tell the browser whether Allow cross-domain requests. In some projects with front-end and back-end separation, the CORS mechanism can be used to realize the front-end's cross-domain request for the back-end interface. When using the Slim framework to develop REST API, we can use middleware (Middleware)

Comparative analysis of Express and Laravel: Choose the framework that suits you better Comparative analysis of Express and Laravel: Choose the framework that suits you better Mar 10, 2024 pm 10:15 PM

Express and Laravel are two very popular web frameworks, representing the excellent frameworks of the two major development languages ​​of JavaScript and PHP respectively. This article will conduct a comparative analysis of these two frameworks to help developers choose a framework that is more suitable for their project needs. 1. Framework Introduction Express is a web application framework based on the Node.js platform. It provides a series of powerful functions and tools that enable developers to quickly build high-performance web applications. Express

See all articles