标签:原来 exports function 有效期 original java export alt ror
后续访问时后端先验证用户凭证
ID+签名
生成复杂字符串
var crypt = {}
const KET = '#$%489!#$%&*156sd'
crypt.cryptUserId = function(userId){
var crypto = require('crypto);
var sign = crypto.createHmac('sha256,KEY');
sign.updata(userId + '');
return sign.digest('hex');
}
module.exports = crypt;
进行设置
//登陆成功,设置Cookies
ctx.cookies.set("sign", crypt.cryptUserId(user.id), {
httpOnly: false,
sameSite: "strict"
});
ctx.cookies.set("userId", user.id, {
httpOnly: false,
sameSite: "strict"
});
验证
var userId = ctx.cookies.get("userId");
var sign = ctx.cookies.get("sign");
var correctSign = crypt.cryptUserId(userId);
if (correctSign !== sign) {
throw new Errow("报告,有人入侵");
}
上面代码,可防御,篡改的 UserId 的入侵
sessionId 为随机生成的字符串,第三方拿不到,就无法入侵
生成复杂字符串
var session = {};
session.set = function(userId, obj) {
var sessionId = Math.random();
if (!cache[sessionId]) {
cache[sessionId] = {};
}
cache[sessionId].conntent = obj;
return sessionId;
};
session.get = function(userId) {
return cache[session] && cache[sessionId].content;
};
module.exports = session;
进行设置
var sessionId = session.set(user.id, {
userId: user.id
});
ctx.cookies.set("sessionId", sessionId, {
httpOnly: ture,
sameSite: "strict"
});
验证
var sessionId = ctx.cookies.get("sessionId");
var sessionObj = session.get(sessionId);
if (!sessionObj || !sessionObj) {
throw new Error("session不存在");
}
var userId = sessionObj.userId;
sessionId 需要持久化,存入数据库,因为内存是有限的。都存在内存中,服务器会出问题
Cookies 与 CSRF 的关系
npm install crypto
var crypto = require("crypto");
var KEY = "#$%^156ssc#$%";
var cipher = crypto.createCipher("des", KEY);
var text = cipher.update("hello word", "utf8", "hex");
text += cipher.final("hex");
console.log(text);//加密后的
var decipher = crypto.createDecipher("des", KEY);
var originalText = decipher.update(text, "hex", "utf8");
console.log(originalText);//原来的
标签:原来 exports function 有效期 original java export alt ror
原文地址:https://www.cnblogs.com/ygjzs/p/12244100.html