快速会话未在浏览器中设置Cookie

时间:2020-11-01 00:29:37

标签: node.js mongodb express session-cookies express-session

因此,我正在使用express-session包来设置Cookie和会话。它还连接到我的MongoDB存储以存储会话。用户登录后,会话可以很好地存储在数据库中,但是浏览器中没有cookie 。我的应用程序正在http://localhost:8080/中运行,而服务器正在http://localhost:5500/中运行。

index.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const expressSession = require('express-session');
const mStore = require('./model/database.js').Mstore;
const routes = require('./control/router.js');
const mongooseConnect = require('./model/database.js').mongooseConnect;


app.use(
   expressSession({ 
      secret: 'my secret', 
      resave: false, 
      saveUninitialized: false,
      store: mStore
   }),
   bodyParser.urlencoded({ extended: true }),
   bodyParser.json(),
   routes
);


mongooseConnect(() => app.listen(process.env.PORT || 5500));

router.js:

const express = require('express');
const router = express.Router();
const notesModel = require('../model/database.js').notesModel;
const userModel = require('../model/database.js').userModel;
const cors = require('cors');

router.options('/login', cors());

router.post('/login', cors(), (req, res) => {
   userModel.findOne({ admin_username: req.body.username, admin_password: req.body.password }, (err, data) => {
      if (err) return console.log(err);
      
      if (data) {
         req.session.isLoggedIn = true; // Saves in database just fine.
         res.status(200).json('Login Success'); // This line works just fine as well.
      } else {
         console.log(req.session.isLoggedIn);
         res.status(401).json('Login Failed: Incorrect ID or Password.');
      }
   });
});

浏览器: enter image description here

1 个答案:

答案 0 :(得分:1)

因此,在给出答案之前,我会说JWT处理会话不是一种安全的方法

如何处理快速会话

首先,您需要以下软件包

npm i express-session connect-mongodb-session或yarn添加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 App /无论您使用哪种登录习惯

//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 
    });
};

现在,您拥有的所有服务器会话Cookie都将以httpOnly的形式出现