How to use cookie-parser middleware in Express
This article mainly introduces an in-depth analysis of the Express cookie-parser middleware implementation example. Now I share it with you and give it as a reference.
Article Introduction
cookie-parser is the middleware of Express, used to implement cookie parsing, and is one of the middleware built into the official scaffolding one.
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 explains in depth the implementation mechanism of Express cookie-parser's signature and verification, and how cookie signature enhances website security.
Text synchronization is included in the GitHub theme series "Nodejs Learning Notes"
Getting Started Example: Cookie Settings and Parsing
First Let’s look at the use of cookie-parser from the simplest example. The default configuration is used here.
Cookie settings: Use Express's built-in method res.cookie().
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);
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(); });
Advanced example: cookie signature and parsing
For security reasons, we usually need to sign cookies.
The example is rewritten as follows, with a few points to note:
When cookieParser is initialized, pass in secret as the signature key.
When setting a cookie, set signed to true, indicating that the cookie to be set will be signed.
When obtaining cookies, you can obtain them through req.cookies or req.signedCookies.
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);
The cookie value before signing is chyingp
, the cookie value after signing is s:chyingp.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0
, decode followed by s:chyingp.uVofnk6k 9mHQpdPlQeOfjM8B5oa6mppny9d 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; };
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 includes the original value.
function sign (val, secret) { return val + '.' + hmac(val, secret); }
Where does the secret
here come from? It is passed in during initialization of cookie-parser
. As shown in the following pseudo code:
var cookieParser = function (secret) { return function (req, res, next) { req.secret = secret; // ... next(); }; }; app.use(cookieParser('secret'));
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:
Extract the original value corresponding to the signed cookie
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; }
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 signatures will be legally verified, and there is no so-called counter-signature.
unsign
The code of the method is as follows:
First, extract the original value A1 and signature value B1 from the incoming cookie value. .
Secondly, use the same secret key to sign A1 to get A2.
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; };
The role of cookie signature
Mainly for security reasons, to prevent cookie tampering and enhance 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 tried 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 signatures 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.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Vue component communication (detailed tutorial)
Detailed analysis of Vue Socket.io source code
Use native JavaScript to achieve the magnifying glass effect
The above is the detailed content of How to use cookie-parser middleware in Express. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

In-depth comparison of Express and Laravel: How to choose the best framework? When choosing a back-end framework suitable for your project, Express and Laravel are undoubtedly two popular choices among developers. Express is a lightweight framework based on Node.js, while Laravel is a popular framework based on PHP. This article will provide an in-depth comparison of the advantages and disadvantages of these two frameworks and provide specific code examples to help developers choose the framework that best suits their needs. Performance and scalabilityExpr

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

How does node+express operate cookies? The following article will introduce to you how to use node to operate cookies. I hope it will be helpful to you!

Express vs. Laravel: Comparing the advantages and disadvantages, which one will you choose? In the field of web development, Express and Laravel are two frameworks that have attracted much attention. Express is a flexible and lightweight web application framework based on Node.js, while Laravel is an elegant and feature-rich web development framework based on PHP. This article will compare the advantages and disadvantages of Express and Laravel in terms of functionality, ease of use, scalability, and community support, and combine

How to use React and Express to build a full-stack JavaScript application Introduction: React and Express are currently very popular JavaScript frameworks. They are used to build front-end and back-end applications respectively. This article will introduce how to use React and Express to build a full-stack JavaScript application. We will explain step by step how to build a simple TodoList application and provide specific code examples. 1. Preparation before starting

How to use Node.js to build a simple blog system Node.js is a JavaScript runtime environment based on the ChromeV8 engine, which can make JavaScript run more efficiently. With the help of Node.js, we can build powerful server-side applications using JavaScript, including blogging systems. This article will introduce you to how to use Node.js to build a simple blog system and provide you with specific code examples. Press

When it comes to choosing a backend framework, both Express and Laravel are very popular choices. Express is a web application development framework based on Node.js, while Laravel is a web application development framework based on PHP. Both have their own advantages, and choosing the framework that best suits you requires considering many factors. The strengths of the Express framework are its flexibility and easy learning curve. The core idea of Express is "small enough and flexible enough", and it provides a large number of middleware
