session ID
和 connect.sid
之间有什么区别?
例如:
console.log('session id =', req.sessionID)
结果:
session id = CCw2pSpdPf8NRKLQpFH-nlFztEzps24Q
还有:
console.log('req.headers =', req.headers)
结果:
req.headers = { 20:51:34
host: 'localhost:3000',
connection: 'keep-alive',
'cache-control': 'max-age=0',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/73.0.3683.75 ' +
'Safari/537.36',
dnt: '1',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
cookie: 'connect.sid=s%3ACCw2pSpdPf8NRKLQpFH-nlFztEzps24Q.P04Tx%2FNboFGXvR34HOjpbeh4ogWy58zs%2Bpyde%2FkuUVs',
'if-none-match': 'W/"2f-u+/xADzzu5HL7bySP/YXVKZBlPc"'
}
CCw2pSpdPf8NRKLQpFH-nlFztEzps24Q
与 connect.sid
如何在中间件中使用它们来验证用户?
最佳答案
session 标识特定的客户端。总体思路是 session 对象和您放入 session 对象中的任何数据都保留在服务器上。当用户向您的服务器发出请求时,他们会提供 session cookie,您的 session 基础设施会查找该 session cookie 并获取适当的 session 对象。然后,您的请求处理程序可以使用该 session 对象以及您放入其中的数据来实现您想要的任何目的。
session 对象中的数据本地存储在您的服务器上,因此它是安全的,不会被客户端弄乱。
How do I use them in a middleware to verify the user?
对于身份验证,通常会在 session 对象中创建某种状态,表示用户是否已通过正确的身份验证。如果没有,您可以向他们索要凭据。如果是这样,您允许请求继续进行。
这是中间件的一些伪代码。
app.get("/login", (req, res) => {
// handle login page
res.sendFile("login.html");
});
app.post("/login", (req, res) => {
// check auth credentials from the login form
if (credentials good) {
req.session.authenticated = true;
res.redirect("/someOtherPage.html");
} else {
req.session.authenticated = false;
res.redirect("/login.html");
}
});
// middleware to allow access of already authenticated
app.use((req, res, next) => {
// check if session already authenticated
if (req.session.authenticated) {
next();
} else {
res.redirect("/login.html");
}
});
// route that relies on previous middleware to prove authentication
app.get("/somethingElse", (req, res) => {
// do something for this authenticated route
});
What the difference between session id and connect.sid?
cookie 有名称和值。默认情况下,快速 session 的 cookie 名称为 connect.sid
。 cookie 的值是一个加密 key ,express-session 将其用作 session 存储的索引。
session ID 是每个 session 对象的内部唯一 ID。它用于 session 存储的内部实现。您实际上不需要担心其中任何一个是什么。它们在内部用于各种内务管理目的。
因此,connect.sid
包含发送到客户端并由客户端返回给服务器的 cookie 值。它故意通过加密来掩盖,并且难以伪造或猜测,以便客户端无法猜测 session 值。 session ID 仅在服务器上使用,并且确实需要这些类型的保护。
关于node.js - express-session - session id 和 connect.sid 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56726972/