服务秘钥生成

机器生成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/")

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值