Home >Web Front-end >JS Tutorial >Comprehensive mastery of Express cookie-parser 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.
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(); });
Out of 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);
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 contains the original value.Where does the secret here come from? It is passed in when cookie-parser is initialized. As shown in the following pseudo code:function sign (val, secret) { return val + '.' + hmac(val, secret); }
var cookieParser = function (secret) { return function (req, res, next) { req.secret = secret; // ... next(); }; }; app.use(cookieParser('secret'));Signed cookie parsingAfter knowing the mechanism of cookie signature, it is clear how to "parse" the signed cookie. At this stage, the middleware mainly does two things:
// 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 the signature will be legally verified, and there is no so-called counter-signature. The code of the unsign method is as follows:
var str = val.slice(0, val.lastIndexOf('.')) , mac = exports.sign(str, secret); return sha1(mac) == sha1(val) ? str : false; };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
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!