机器生成keys: 有uuid和guid
全局唯一标识符uuid
npm install uuid -D
它有多个版本v1,v2,v4,v5,我们使用v4
const uuid = require('uuid/v4');
console.log(uuid())
写成小工具:
生成一个有1024项的数组,并且每个项有1024位。
const uuid = require('uuid/v4');
const fs = require('fs');
const path = require('path');
let N = 1024;
let arr = [];
for(let i = 0; i < N; i++) {
let str = '';
for(let j = 0; j < 32; j++) {
str += uuid().replace(/\-/g, '');
}
arr.push(str);
}
// 生成文件
fs.writeFileSync(path.resolve(__dirname, '../.keys'), JSON.stringify(arr));
console.log(`生成完成:${N}个秘钥`)
读取key:
const Koa = require("koa");
const opn = require("opn");
const fs = require("promise-fs");
const path = require("path");
let server = new Koa();
server.listen(8000);
server.keys = JSON.parse(fs.readFileSync(path.resolve(__dirname, '.keys')).toString());
console.log(`读取了${server.keys.length}个key`);
server.use(async ctx=>{
if(ctx.url=='/favicon') return;
ctx.cookies.set('user', 'enoch1', {signed: true}) // 设置cookie
console.log(ctx.cookies.get('user'));// 获取cookie
})
opn("http://localhost:8000/")
如果需要跟换key,只需要重新生成一个即可。
cookie的参数:
signed: 签名
maxAge:有效期
const Koa = require("koa");
const fs = require("promise-fs");
const path = require("path");
let server = new Koa();
server.listen(8000);
server.keys = JSON.parse(fs.readFileSync(path.resolve(__dirname, '.keys')).toString());
console.log(`读取了${server.keys.length}个key`);
server.use(async ctx=>{
if(ctx.url=='/favicon') return;
ctx.cookies.set('user', 'enoch1', {
signed: true, // 签名
maxAge: 86400 * 1000, // 单位是ms
})
})
path:cookie的路径
向上访问:
假设当前cookie在/a/b,除了自身路径外,还可以访问/a,/。但是不能访问/a/b/c
path: ‘/’
domain: cookie的域名
向上访问
设置在一级域名
secure: 安全cookie(不常用)
https可以访问
http不能访问
httpOnly: 只能通过http访问(不常用)
只有服务端能访问,前台JS不能访问
防止前台js操作
加上try
const Koa = require("koa");
// const opn = require("opn");
const fs = require("promise-fs");
const path = require("path");
let server = new Koa();
try {
server.keys = JSON.parse(fs.readFileSync(path.resolve(__dirname, '.keys')).toString());
console.log(`读取了${server.keys.length}个key`);
} catch (e) {
console.log('读取keys文件失败,请先生成key');
return;
}
server.use(async ctx=>{
if(ctx.url=='/favicon') return;
ctx.cookies.set('user', 'enoch1', {
signed: true, // 签名
maxAge: 86400 * 1000, // 单位是ms
})
})
server.listen(8000);
// opn("http://localhost:8000/")