所以我可以为您提供一个使用 express-session 和 connect-mongodb-session 来处理会话的替代解决方案,这往往是流行且有些安全的服务器会话处理解决方案
首先你需要以下包
npm i express-session connect-mongodb-session 或 yarn add express-session connect-mongodb-session
现在我们有了需要设置 mongoStore 和 express-session 中间件的包:
//Code in server.js/index.js (Depending on your server entry point)
import expressSession from "express-session";
import MongoDBStore from "connect-mongodb-session";
import cors from "cors";
const mongoStore = MongoDBStore(expressSession);
const store = new mongoStore({
collection: "userSessions",
uri: process.env.mongoURI,
expires: 1000,
});
app.use(
expressSession({
name: "SESS_NAME",
secret: "SESS_SECRET",
store: store,
saveUninitialized: false,
resave: false,
cookie: {
sameSite: false,
secure: process.env.NODE_ENV === "production",
maxAge: 1000,
httpOnly: true,
},
})
);
现在会话中间件已准备就绪,但现在您必须设置 cors 以接受您的 ReactApp,以便传递 cookie 并由服务器将其设置在那里
//Still you index.js/server.js (Server entry point)
app.use(
cors({
origin: "http://localhost:3000",
methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
credentials: true,
})
);
现在我们的中间件都设置好了,让我们看看你的登录路径
router.post('/api/login', (req, res)=>{
//Do all your logic and now below is how you would send down the cooki
//Note that "user" is the retrieved user when you were validating in logic
// So now you want to add user info to cookie so to validate in future
const sessionUser = {
id: user._id,
username: user.username,
email: user.email,
};
//Saving the info req session and this will automatically save in your mongoDB as configured up in sever.js(Server entry point)
request.session.user = sessionUser;
//Now we send down the session cookie to client
response.send(request.session.sessionID);
})
现在我们的服务器已准备就绪,但现在我们必须修复在客户端发出请求的方式,以便此流程可以 100% 工作:
以下代码:处理登录的 React 应用程序
//So you will have all your form logic and validation and below
//You will have a function that will send request to server
const login = () => {
const data = new FormData();
data.append("username", username);
data.append("password", password);
axios.post("http://localhost:5000/api/user-login", data, {
withCredentials: true, // Now this is was the missing piece in the client side
});
};
现在有了所有这些,您现在拥有作为 httpOnly 的服务器会话 cookie