使用 signed 属性进行cookie加密
const express = require("express"); const cookieParser = require("cookie-parser"); var app = express(); app.use(cookieParser('secret')); app.get("/",function(req,res){ res.send("主页"); }); //获取cookie app.use(function(req,res,next){ console.log(req.signedCookies.name); next(); }); //设置cookie app.use(function(req,res,next){ console.log(res.cookie("name","zhangsan",{httpOnly: true,maxAge: 200000,signed: true})); res.end("cookie为:"+req.signedCookies.name); }); app.listen(8080);
签名原理
Express用于对cookie签名,而cookie-parser则是实现对签名的解析。实质是把cookie设置的值和cookieParser(‘secret’);中的secret进行hmac加密,之后和cookie值加“.”的方式拼接起来。
当option中signed设置为true后,底层会将cookie的值与“secret”进行hmac加密;