cookie and encryption

command:

express --view=ejs cookieapp

cnpm install

nodemon ./bin/www

 

The basic content of app.js

// 错误处理
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
// 输出日志
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
// 视图设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// express中间件
app.use(logger('dev')); //日志信息解析
// 请求对象解析
app.use(express.json()); //body解析
app.use(express.urlencoded({
  extended: false
})); //post解析
app.use(cookieParser()); //cookie解析
app.use(express.static(path.join(__dirname, 'public')));

// 如果没有静态文件,走下面
// 路由匹配
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
// 如果也没有路由匹配,就报404错误,或者使用页面渲染
// 设置404的中间件
app.use(function (req, res, next) {
  res.render('404.ejs');
  // next(createError(404));
});

// error handler
// 处理错误的中间件
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

 

Set cookie

router.get('/setcookie', function (req, res) {
  // 基础设置cookie,有效期默认为1个会话(浏览器关闭即失效)
  // res.cookie("isLogin", "true");
  // 10s ;httpOnly: true  :前端不能发现,隐藏isLogin=true,但是http协议可以看见,防止前端操作
  res.cookie("isLogin", "true", {
    maxAge: 100000,
    httpOnly: true
  });

  res.send("cookie设置成功");
})

router.get('/admin', function (req, res) {
  if (req.cookies.isLogin == 'true') {
    res.send("成功");
  } else {
    res.send("失败");
  }
})

About setting cookie parameters:

  1. domain: domain name
  2. name=value: key-value pair, you can set the Key/Value to be saved, note that the name here cannot be the same as the names of other attribute items
  3. Expires: Expires time (seconds), the cookie will become invalid after a set time point, such as expires=Wednesday, 09-Nov-99 23:12:40 GMT.
  4. maxAge: The maximum expiration time (milliseconds), after which the set expires.
  5. secure: When the secure value is true, the cookie is invalid in HTTP and only valid in HTTPS.
  6. Path: Indicates that the cookie can be accessed under that route.
  7. httpOnly: It is Microsoft's extension to COOKIE. If the "httpOnly" attribute is set in COOKIE, the COOKIE information will not be read by the program (JS script, applet, etc.) to prevent XSS attacks.
  8. singed: Indicates whether to sign the cookie, set to true to sign the cookie, so you need to use res.signedCookies instead of res.cookies to access it. The tampered signed cookie will be rejected by the server, and the cookie value will be reset to its original value.

httpOnly: true: the front-end cannot be found, hide isLogin=true, but the http protocol can be seen, preventing front-end operation

 

 

Encrypted cookie

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

signed: true means encryption

router.get('/setcookie', function (req, res) {
  // 设置加密操作
  // signed: true表示加密
  res.cookie('login', 'true', {
    signed: true
  });
  res.send("cookie设置成功");
})

The encrypted value is in req.signedCookies, not in req.cookies

router.get('/adminSecret', (req, res) => {
  // 加密之后的值在req.signedCookies,不在req.cookies中
  console.log(req.signedCookies);
  if (req.signedCookies.login == 'true') {
    res.send("加密cookie,成功");
  } else {
    res.send("加密cookie,失败");
  }

})

// 加密原理解析
router.get('/secret', (req, res) => {
  // 需要加密的字符串
  let password = '123456';
  // 使用的加密算法
  let sf = crypto.createHash('md5');
  // update:用来加密
  sf.update(password);
  // 加密的二进制数据以字符串的形式
  let content = sf.digest('hex');
  res.send(content);
})

// 自己定义加密cookie
router.get('/appSecret', (req, res) => {
  let secretStr = jiami('true');
  res.cookie('register', secretStr);
  // 设置将加密的密文和明文内容放置在某个位置
  setSecretCookie("true", secretStr);
  res.send("cookie加密成功");
})

// 获取自己加密的cookie值 
router.get('/getAppSecret', (req, res) => {
  let strSecret = req.cookies.register;
  content = getSecretCookie[strSecret];
  console.log("解密后register的内容:", content);
  res.send("解密后register的内容:" + content);
})


let secretCookie = {

}

function setSecretCookie(str, secretStr) {
  secretCookie[secretStr] = str;
}

function getSecretCookie() {
  return secretCookie[secretStr];
}

// 密码后面跟的随机值
let randomNum = Math.random();

function jiami(str) {
  // 需要加密的字符串
  let password = str;
  password = password + 'xxy' + randomNum;
  // 使用的加密算法
  let sf = crypto.createHash('md5');
  // update:用来加密
  sf.update(password);
  // 加密的二进制数据以字符串的形式
  let content = sf.digest('hex');
  // res.send(content);
  return content;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/small_rain_/article/details/112969412