In-depth analysis of the Express cookie-parser middleware implementation example,

Source: Internet
Author: User
Tags hmac sha1

In-depth analysis of the Express cookie-parser middleware implementation example,
Document Introduction

Cookie-parser is an Express middleware used to parse cookies. It is one of the built-in middleware of official scaffolding.

It is very simple to use, but occasionally encountered problems during use. This is generally because you do not know the signature and authentication mechanism of Express + cookie-parser.

This article provides an in-depth explanation of how Express + cookie-parser signatures and verification are implemented, and how cookie signatures enhance website security.

The text is recorded simultaneously in the GitHub topic series Nodejs study notes.

Example: cookie settings and resolution

First, let's look at the use of cookie-parser in the simplest example. The default configuration is used here.

  1. Cookie setting: Use the Express built-in method res. cookie ().
  2. Cookie resolution: Use the 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); // The second access, outputs chyingp next () ;}); app. use (function (req, res, next) {res. cookie ('Nick ', 'chingp'); res. end ('OK') ;}); app. listen (0, 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();});
Example: cookie signature and resolution

For security reasons, we usually need to sign cookies.

The example is rewritten as follows:

  1. When cookieParser is initialized, secret is input as the signature key.
  2. When setting the cookie, set signed to true to sign the cookie to be set.
  3. You can use req. cookies or req. signedCookies to obtain cookies.
Var express = require ('express '); var cookieParser = require ('cookie-parser'); var app = express (); // initialize the middleware, the first input parameter is singed secretapp. 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) {// pass in the third parameter {signed: true}, indicating that the cookie is digest calculated by res. cookie ('Nick ', 'chingp', {signed: true}); res. end ('OK') ;}); app. listen (0, 3000 );

The cookie value before signature ischyingp , The signed cookie value iss%3Achyingp.uVofnk6k%2B9mHQpdPlQeOfjM8B5oa6mppny9d%2BmG9rD0, After decode iss:chyingp.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0 .

Next we will analyze how the cookie signature and resolution are implemented.

Analysis of cookie signature and verification implementation

Express completes the cookie value signature, and cookie-parser implements signature cookie resolution. The two share the same key.

Cookie Signature

Express uses the res. cookie () method to set cookies (including signatures.

The simplified code is as follows:

Res. cookie = function (name, value, options) {var secret = this. req. secret; var signed = opts. signed; // If options. if signed is true, the cookie is signed if (signed) {val ='s: '+ sign (val, secret);} this. append ('set-cookies', Cookie. serialize (name, String (val), opts); return this ;};

Sign is the signature function. The pseudocode is as follows, which is to splice the original cookie value with the value after hmac.

Key: the cookie value after the signature, including the original value.

function sign (val, secret) { return val + '.' + hmac(val, secret);}

Heresecret Where did it come from? Yescookie-parser Passed in during initialization. The pseudocode below is as follows:

var cookieParser = function (secret) { return function (req, res, next) {  req.secret = secret;  // ...  next(); };};app.use(cookieParser('secret'));

Signature cookie Parsing

After learning about the cookie signature mechanism, it is clear how to "parse" the signature cookie. At this stage, middleware mainly implements two tasks:

  1. Extract the original value corresponding to the signature cookie
  2. Verify that the signature cookie is valid

The implementation code is as follows:

// Str: signed cookie, such as "s: chyingp. uVofnk6k + 9mHQpdPlQeOfjM8B5oa6mppny9d + mG9rD0 "// secret: Key, for example," secret "function signedCookie (str, secret) {// check whether the start of s, make sure that only the signed cookie is parsed if (str. substr (0, 2 )! ='S: ') {return str;} // check whether the signature value is valid. If the value is valid, true is returned. Otherwise, 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 cookie value. Only the unsign method name is confusing.

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

unsign The method code is as follows:

  1. First, extract the original A1 and signature B1.
  2. Second, sign A1 with the same key to obtain A2.
  3. Finally, judge 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;};
Functions of cookie Signature

Mainly for security considerations, prevent cookie tampering and enhance security.

Let's take a small example to see how the cookie signature is tamper-resistant.

Based on the preceding example. Assume that the website uses the cookie nick to identify who is currently logged on. In the previous example, in the cookie of the login user, the value of nick is as follows: (After decode)

s:chyingp.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0

At this time, someone tries to modify the cookie value to forge an identity. For example, modify it to xiaoming:

s:xiaoming.uVofnk6k+9mHQpdPlQeOfjM8B5oa6mppny9d+mG9rD0

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

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

Can signature ensure security?

Of course not.

In the example in the previous section, the cookie value nick is used only to determine which user is logged on. This is a very bad design. Although the secret key is unknown, it is difficult to forge a signature cookie. However, if the user name is the same, the signature is also the same. In this case, it is easy to forge.

In addition, open-source component algorithms are open to the public, so the security of the key becomes the key, to ensure that the key is not leaked.

There are many more, which are not shown here.

Summary

This article mainly introduces the signature and resolution mechanism of Express + cookie-parser in depth.

In many similar summary articles, it is a common mistake to describe the cookie signature as encryption. Readers should pay attention to it.

The signature section introduces some simple security knowledge. If you are not familiar with this section, you can leave a message. For ease of explanation, some paragraphs and words may not be rigorous enough. If any, please note that.

Related Links

Https://github.com/expressjs/cookie-parser

Https://github.com/chyingp/nodejs-learning-guide

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.