Current location - Quotes Website - Personality signature - How to use cookie-parser middleware in Express
How to use cookie-parser middleware in Express
This paper mainly introduces an example of in-depth analysis of Express cookie-parser middleware, which is now shared with you for your reference.

Cookie-parser is the middleware of Express, which is used to parse cookies, and it is one of the middleware built in the official scaffolding.

It is very simple to use, but you will occasionally encounter problems in the process of use. Generally, it is caused by ignorance of the signature and verification mechanism of Express+cookie-parser.

This paper expounds the implementation mechanism of Express+cookie-parser's signature and verification, and how cookie signature can enhance the security of the website.

Text synchronization is included in the GitHub theme series "Nodejs Learning Notes"

Introductory example: cookie setting and parsing Let's look at the use of cookie-parser from the simplest example, where the default configuration is adopted.

Cookie setting: use the built-in method res.cookie () of Express.

Cookie parsing: use cookies to parse middleware.

var express = require(' express ');

var cookie parser = require(' cookie-parser ');

var app = express();

app . use(cookieParser());

app.use(function (req,res,next) {

console . log(req . cookies . nick); //Visit for the second time, and output chyingp.

next();

});

app.use(function (req,res,next) {

res.cookie('nick ',' chying p ');

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 signing and parsing For security reasons, we usually need to sign cookies.

The example is rewritten as follows, with several considerations:

When the cookieParser is initialized, secret is passed in as the signed key.

When setting cookies, set signed to true, which means signing the cookies to be set.

Cookies can be obtained through req.Cookiess or req.signedCookies.

var express = require(' express ');

var cookie parser = require(' cookie-parser ');

var app = express();

//Initialize the middleware, and the first parameter passed in is singed secret.

app . use(cookieParser(' secret '));

app.use(function (req,res,next) {

console . log(req . cookies . nick); // chyingp

console . log(req . signed cookies . nick); // chyingp

next();

});

app.use(function (req,res,next) {

//Pass in the third parameter {signed: true}, indicating that cookie are to be summarized.

res.cookie('nick ',' chyingp ',{ signed:true });

RES . end(' ok ');

});

app . listen(3000); The cookie value before signature is chyingp, and the cookie value after signature is s% 3achiingp.uvofnk6k% 2b9mhqpdlqeofjm8b6amp pny9d% 2bmg9rd0. After decoding, it is s: Chying p.uvofnk6k+9mhqpdlqeofjm8b5amp pny9d+mg9rd0.

Let's analyze how the signature and parsing of cookie are realized.

Cookie signature and verification implement parsing expression to complete the signature of cookie value, and cookie-parser implements the parsing of signature cookie. Two * * * use the same key.

Cookie signature

The setting of cookie (including signatures) by Express is realized by the method res.cookie ().

The simplified code is as follows:

Res.cookie = function (name, value, option) {

var secret = this . req . secret;

var signed = opts.signed

//If options.signed is true, the cookie is signed.

If (signature) (

val = 's:' + sign(val,secret);

}

this.append('Set-Cookie ',cookie.serialize(name,String(val),opts));

Return this;

}; Sign is a signature function. The pseudo-code is as follows, which is actually a concatenation of the original value of cookie and the value after hmac.

Knock on the blackboard and underline the point: the signed cookie value contains the original value.

Function symbol (val, secret) (

Returns val +'. '+ hmac(val, secret);

} Where did the secret come from? It was passed in when cookie-parser was 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 ')); Signature cookie parsing

Knowing the mechanism of cookie signature makes it clear how to "parse" the signature cookie. At this stage, middleware mainly does two things:

Extract the original value corresponding to the signature cookie.

Please verify that the signature cookie is legal.

The implementation code is as follows:

// str: a signed cookie, such as "s: chiying p.uvofnk6k+9mhqpdplqofjm8b6amp pny9d+mg9rd0".

// secret: key, such as "secret"

Function signedCookie(str, secret) (

//Check whether it starts with s: to ensure that only signed cookie are parsed.

if (str.substr(0,2)! == 's:') {

Returns a string;

}

//Check whether the signed value is legal, and return true if it is legal, otherwise return false.

var val = unsign(str.slice(2),secret);

If (val! = = False)

Return val

}

Returns false

} It is relatively simple to determine the original value of the extracted cookie. It's just that the unsign method name is confusing.

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

The code of the unsign method is as follows:

First, the original value A 1 and the signature value B 1 are extracted from the incoming cookie value.

Secondly, A 1 is signed with the same key to get A2.

Finally, according to whether A2 and B 1 are equal, whether the signature is legal or not is judged.

exports.unsign = function(val,secret){

var str = val.slice(0,val.lastIndexOf(' . ')))

,mac = exports.sign(str,secret);

return sha 1(MAC)= = sha 1(val)? str:false;

}; The function of cookie signature is mainly for security reasons, to prevent cookies from being tampered with and to enhance security.

Take a small example to see how cookie signature is tamper-proof.

Expand on the basis of the previous example. Suppose the website uses cookie nick to distinguish the currently logged-in users. In the previous example, in the cookie of the logged-in user, the corresponding value of nick is as follows: (after decoding)

s:chying p . uvofnk 6k+9mhqpdplqeofjm 8 b5 a6 mppny 9d+mg9rd 0

At this point, someone tried to modify this cookie value to achieve the purpose of forging identity. For example, change it to Xiao Ming:

s:Xiaoming . uvofnk 6k+9mhqpdplqeofjm 8 b5 a6 mppny 9d+mg9rd 0

After receiving the request, the website parses the signature cookie and finds that the signature verification failed. From this, it can be judged that cookies are forged.

Hmac ("Xiao Ming", "Secret")! = = " uvofnk 6k+9mhqpdplqeofjm 8 b5 a6 mppny 9d+mg9rd 0 "

Is signature a guarantee of security? Of course not.

In the example in the previous section, it is a very bad design to judge which user logs in only by the value of cookie nick. Although it is difficult to forge signature cookie when the key is unknown. But in the case of the same user name, the signature is the same. In this case, it is actually very easy to forge.

The above is what I arranged for you, and I hope it will help you in the future.

Related articles:

Vue component communication (detailed tutorial)

Detailed analysis of Vue Socket.io source code

Using native JavaScript to realize magnifying glass effect