To read more articles in this series please visit myMaking a blog, sample code please visithere.
A Cookie is introduced
Cookie is stored in the browser. When the browser requests the server, the data in the Cookie will be sent to the server, which is often used to verify user information.
However, because cookies are stored in browsers, they are vulnerable to tampering and have poor security.
Cookies are processed using cookie-parser
To handle cookies, use the middleware cookie-parser
Read the Cookie
Example code: /lesson05/server.js
When cookie-Parser is used, cookies need to be parsed through server.use(cookieParser()) first, and then the value of cookies can be read in the property of req.cookies.
In the browser open http://localhost:8080/cookie, write a cookie in the console {” userName “:” lee “}.
Cookie server.use(cookieParser()) server.get()'/cookie', (req, res, next) => {// Read Cookie console.log(req.cookies) res.send(' cookies:${JSON.stringify(req.cookies)}`)})Copy the code
In the browser open http://localhost:8080/cookie, the service side to print the results as follows: {” userName “:” lee “}.
Set the Cookie
Example code: /lesson05/server.js
Cookies can be set using the res.cookie method that comes with Express.
The first argument to the method is the name of the set property, the second argument is the value of the property, and the third argument is the configuration item, for example:
server.get('/cookie', (req, res, next) => {req, res, next)'userName'.'lee'{// Set the Cookie to be accessible only by the server, i.e. the front-end JavaScript cannot access document. Cookie to obtain this value, but the console can still view and modify httpOnly:true// Only cookies requested through HTTPS are used, otherwise they are considered wrong cookies // secure:trueWhen the browser searches for cookies, the subdomain (such as translate.google.com) can access the cookies under the main domain (google.com). The main domain (google.com) cannot access the subdomain (e.g. translate.google.com) Cookie // local test can be directly set to localhost domain:'localhost'// Set the path to save the Cookie. When the browser searches for cookies, subpaths (such as /map) can access the root path ('/'), while the root path ('/'Unable to access Cookie path set under child path (e.g. /map) :'/', // Set Cookie expiration to 14 days // Expires: New Date(new Date().getTime() + 14 * 86400000), // set the Cookie expiration time to 14 days after maxAge: 14 * 86400000,}) // Read Cookie console.log(req.cookies) res.send(' cookies:${JSON.stringify(req.cookies)}`)})Copy the code
In the browser console, you can see that the Cookie is set to {“userName”:”lee”} and is valid for 14 days.
The signature of the Cookie
Example code: /lesson05/server.js
The Cookie signature encrypts the Cookie with a key stored on the server. The data stored in the Cookie is encrypted with the key. Therefore, if the client modifies the Cookie, the server verification fails.
Set the key
To sign a Cookie, pass a string key to the first parameter of the cookieParser:
Use (cookieParser(// Signature key that needs to be kept secret and stored only on the server side'NpLRTpy1vbBzEw2JcAxpf970kOk2RViDn5wKwrMv'
))
Copy the code
Signature cookies
We can start setting the signed Cookie by setting the signed: true property in the res. Cookie method configuration parameter:
res.cookie('password'.'test123', {
httpOnly: true,
domain: 'localhost',
path: '/', maxAge: 14 * 86400000, // open the Cookie signature mode signed:true
})
Copy the code
In the browser open http://localhost:8080/cookie, you can see the Cookie is set the password attribute, its value is s % 3 atest123. HrZ44MCUeLXj0uZAzTpCXWduflOsmfBs5XsuK4eTMvg.
If using decode decodeURIComponent method, the results for s: test123. HrZ44MCUeLXj0uZAzTpCXWduflOsmfBs5XsuK4eTMvg.
Its meaning is as follows:
s
Indicates that the Cookie is a signed Cookietest123
Represents the value of the Cookie settingHrZ44MCUeLXj0uZAzTpCXWduflOsmfBs5XsuK4eTMvg
Represents the signature of the value, meaning that when the Cookie is received by the server, the server key pair is usedtest123
For signature, and then withHrZ44MCUeLXj0uZAzTpCXWduflOsmfBs5XsuK4eTMvg
Only use it if it is correct.
You can see that signedCookies: {“password”:”test123″} is printed on the server.
The Cookie of the signature is modified on the client
If the user in the client to make the changes to your signature of cookies, in the browser console, for example, change the password to s % 3 atest456. HrZ44MCUeLXj0uZAzTpCXWduflOsmfBs5XsuK4eTMvg.
In this case, signedCookies: {“password”:false} is displayed on the server, indicating that the verification fails.
At the same time in the browser Cookie value was modified in order to s % 3 atest123. HrZ44MCUeLXj0uZAzTpCXWduflOsmfBs5XsuK4eTMvg.
The verification fails unless the user modifies the signature of the Cookie when changing the value.
But since the signature is computed by the server-side key, this value is usually secure.
However, signing cookies consumes more Cookie storage space, and cookies can only be stored in 4K in a browser. Therefore, signatures cannot be abused and can only be used to protect important data.